-2

I want to the match the string /word/test. I tried \/word\/(.*) on regex101 and that works perfectly. It puts test in group1 and that's the part I want to extract.

But when I try this in Java I can't get it to work. This is my java:

Pattern p = Pattern.compile("\\/word\\/(.*)\\/");

But this comes out with no matches. I've been using freeformatter to test out the java regex but have been unable to get anything to match. I think the forward slash is throwing things off but I've tried so many different. I've looked at this thread and tried \\\\/ but that doesn't work either.

Community
  • 1
  • 1
Richard
  • 5,840
  • 36
  • 123
  • 208
  • 1
    You do not have trailing Slash in your original regex101, why do you use it in Java? – hoaz Mar 10 '17 at 19:20
  • just tested on freeformatter with trailing slash on input (and some escaping slashes removed for their webform) and it worked. – gnomed Mar 10 '17 at 19:21
  • 1
    more important question, what happened to your reputation score? – hoaz Mar 10 '17 at 19:22

2 Answers2

1
Pattern p = Pattern.compile("/word/(.*)");
csirmazbendeguz
  • 598
  • 4
  • 13
0

Pattern p = Pattern.compile("/word/(.*)/");

The trailing / at the end of the pattern will not work for /word/test because it's looking for /word/test/. If you want the trailing slash to be optional, change it to something like:

Pattern p = Pattern.compile(/word/(.*)(/)?");

NAMS
  • 983
  • 7
  • 17