yarek
yarek

Reputation: 12044

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

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:

Any clue ?

regards

Upvotes: 0

Views: 1118

Answers (5)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

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.

Upvotes: 0

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

for last occurrence

^code:[ ]([0-9a-f-]+)(?:(?!^code:[ ])[\s\S])*Paris

you have to customize with your text.

Please refer this:

Regex match everything from the last occurrence of either keyword

Match from last occurrence using regex in perl

RegExp: Last occurence of pattern that occurs before another pattern

Regex get last occurrence of the pattern

Upvotes: 1

Jan
Jan

Reputation: 1042

less tracebacks and without relying on greediness:

\d+[^0-9]*Paris

Upvotes: 1

Andrew
Andrew

Reputation: 5340

Try this regex:

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

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

Upvotes: 1

Lajos Veres
Lajos Veres

Reputation: 13725

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

 \d+.*?Paris

Upvotes: 0

Related Questions