4

I am trying to match an occurrence with the regex:

to(.*?) CITY[\d]

against

John from beautiful CITY1 in sdfsf to dsfs in sf to abc CITY2 to CITY3 for 3 days

I get two matches :

to dsfs in sf to abc CITY2 
to CITY3

My problem is that I want a regular exp using which I could get a match as "to abc CITY2" instead of "to dsfs in sf to abc CITY2".

I read about lazy quantifiers but couldn't apply it in this scenario.

1
  • I think you need to change the expression/logic to something like this to(?: \w+)? CITY\d Commented Nov 5, 2014 at 11:22

1 Answer 1

3
\bto\b(?:(?!\bto\b).)*?CITY\d+

Try this.See demo.

http://regex101.com/r/iZ9sO5/7

Here we use negative lookahead to ensure the any character after to does not match to.So it will pick the nearest to to City.

(?!\bto\b) negaitve lookahead to not match to

.)* quantifying it

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It works. @HamZa has suggested a cleaner regex.

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.