Reputation: 1029
In this url:
http://example.com/SearchResult-Empty.html?caty[]=12345&caty[]=45678
I am trying to use the following regex to grab the first occurence of caty which should be "12345". However, instead, the regex below is giving me the final occurrence 45678. I tried using the "?" limiter to make it non-greedy per other stack overflow questions, but it isn't working. How can I do this?
^SearchResult(?:.*)(caty)(?:.*)\=([0-9]+)\&?$
Upvotes: 2
Views: 108
Reputation: 14361
As far as I can tell, two things are messing you up:
^
and $
seem to be forcing the regex to produce bad matches.*
instead of non-greedy .*?
SearchResult(?:.*?)(caty)(?:.*?)\=([0-9]+)\&?
Should do the job
Upvotes: 1
Reputation: 881463
^SearchResult(?:.*)(caty)(?:.*)\=([0-9]+)\&?$
^^
.*
is greedy matching, meaning that it will go the the last occurrence of caty
rather than the first. You could check that by providing three caty
's in the input string and it will then skip the first two.
.*?
makes it non-greedy (aka reluctant), which will consume as little as possible to make a match - stopping at the first occurrence of caty
.
Upvotes: 1