Greggz
Greggz

Reputation: 1799

Java Regex: Matcher.find problems

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

Upvotes: 3

Views: 387

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

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)

Upvotes: 1

Related Questions