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.

Richard
  • 106,783
  • 21
  • 203
  • 265
RVP
  • 43
  • 3
  • I think you need to change the expression/logic to something like this [`to(?: \w+)? CITY\d`](http://regex101.com/r/aM5oU3/1) – HamZa Nov 05 '14 at 11:22

1 Answers1

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

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
vks
  • 67,027
  • 10
  • 91
  • 124