regex: how to include the first occurrence before the pattern?

1.1k Views Asked by At

My text is:

120 something 130 somethingElse Paris

My goal is to capture 130 somethingElse Paris which means only the last occurrence of number BEFORE Paris

I tried:

\d+.*Paris

But this captures the WHOLE string (from first occurrence of digit)

The rule is:

  • Capture everything before Paris until first occurrence of digit is found.

Any clue ?

regards

5

There are 5 best solutions below

0
On

You can use this pattern:

(\d+\D*?)+Paris

other occurences of the capturing group are overwritten by the last.

The lazy quantifier *? is used to force the pattern to stop at the first word "Paris". Otherwise, in a string with more than one word "Paris", the pattern will return the last group after the last word "Paris" with a greedy quantifier.

1
On

You should add a ? after the * to make it un-greedy. Like this:

 \d+.*?Paris
0
On

Try this regex:

/(\d+[^\d]*Paris)/gi

http://jsfiddle.net/rooseve/XDgxL/

0
On

less tracebacks and without relying on greediness:

\d+[^0-9]*Paris
0
On