marwils
marwils

Reputation: 473

Regex: Find last occurrence of digit pair

I'm trying to find the last match of a digit pair in some kinds of strings like these:

123f64swfW68F43
123f64swfW6843
123f64swfW6843sad
123f64swfW6843sa3d

In all of them the matching result should be 43. I tried my best and came to:

/(\d{2})(?!.*\d)/

But this works only for the first three strings.

Please note that I want to do this in one regular expression and without any further scripting.

Thanks for your help!

Upvotes: 2

Views: 857

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

You may use

\d{2}(?!\d|.*\d{2})

See the regex demo. It basically means "match 2 consecutive digits that are not immediately followed with a digit and that not followed with any 2 consecutive digits anywhere to the right of those two digits".

Details

  • \d{2} - two digits
  • (?!\d|.*\d{2}) - that are not followed with a digit or with any two digits aftr any 0+ chars other than line break chars.

Alternatively, you may use

/.*(\d{2})/

and grab Group 1 value. See the regex demo. This regex means "match all text it can to the last two digits, and capture the two digits in a separate memory buffer".

Details

  • .* - any 0+ chars other than line break chars, as many as possible
  • (\d{2}) - Capturing group 1: two digits

Upvotes: 1

Related Questions