3

I am having trouble distinguishing two templates when I aplly match.find().

String template1 = "GET /boards/(.+?)";
String template2 = "GET /boards/(.+?)/lists";  

When given the following input : "GET /boards/boardName/lists" , it matches with the first template instead of the second. What am I doing wrong ?

Thanks in advance

3
  • 2
    In the first one, +? will still match (non-greedily) the character after the last forward slash because . matches any single character except newline. Therefore, it matches on this expression first. If you don't want the first expression to match, change it to GET /boards/([^/]+)$ Commented Oct 17, 2015 at 20:12
  • 1
    Are you sure that input won't actually match both? Commented Oct 17, 2015 at 20:12
  • 2
    In the first case, group 1 contains boardName/lists. In the second case group 1 contains boardName. Both patterns will match. Commented Oct 17, 2015 at 20:13

1 Answer 1

1

That's because of that (.+?) will match every combinations of characters with length 1 or more which will make your regex engine match the following part :

boardName/lists

Also note that if you first try the following regex :

GET /boards/(.+?)/lists

It will match the string too but the difference is that in this regex the group 1 will be contain boardName, but in the first one the group 1 will be b (because of ? which makes .+ a none greedy pattern ).

If you want that the first regex not match your string you can use a negative look ahead and a negated character class to match the strings that are not followed by word list :

GET /boards/([^/]+)(?!lists)
Sign up to request clarification or add additional context in comments.

3 Comments

@hwnd Yep, that will match the strings that just have one word after GET /boards/.
Can you please check this: ideone.com/u75KTR I am getting different output then what you have mentioned.
@YoungHobbit yep, sorry I missed that point, the first regex group 1 will be the character b because of none greedy matching

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.