jeudi 13 juillet 2017

Cannot match regex pattern in java

I'm failing to match a regex in java.

So I have a regex to match a specific link type:

(http?\w:\/\/)(w{3})?(.linkname.com\/p\/\w+)\/?($)?

it will match for example:

http://ift.tt/2tO6kAF

As can be verified online. Try it (http://regexr.com/)

The problem is that, in Java, it doesn't work.

MCVE:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

   public static void main(String[] args){


      String rndTxt = "HHHahahahaha \n www. http: ldakdoAPF http://ift.tt/2tkBPPy SUFUSF HTTP: http:111";

      //I had to escape each \
      Pattern pattern = 
      Pattern
      .compile("(http?\\w:\\/\\/)(w{3})?(.linkname.com\\/p\\/\\w+)\\/?($)?");

      Matcher matcher = pattern.matcher(rndTxt);

      if (matcher.find())
         System.out.println( matcher.group(1) ); //Either finds null or only a segment, depending on tweaks of regex and text
  }
}

This is more about why it works on regex simulators online and not in java, than about finding the specific regex I need, or why my regex sucks anyway (I just learned how to do it 10 minutes ago).

What am I missing?

Aucun commentaire:

Enregistrer un commentaire