user1775718
user1775718

Reputation: 1578

Regex to capture all numbers in a string that ends with a number

I'm trying to write a regex that captures all the numbers in a string BUT only if the string ends with numbers.

I worked out the pattern would require a repeating capture group:

^(\D*(\d+))+$

So

My problem is that it seems that in repeated capture groups you only get the last match returned to you. (demo)

Can anyone show me where I'm going wrong?

Upvotes: 3

Views: 134

Answers (1)

anubhava
anubhava

Reputation: 784998

You may use this regex with a lookahead:

\d+(?=(?:\w+\d)?\b)

RegEx Demo

RegEx Breakdown:

  • \d+: Match 1+ digits
  • (?=: Start Lookahead assertion
    • (?:\w+\d)?: Optionally match 1 or more word characters followed by a digit
    • \b: Word boundary
  • ): End Lookahead assertion

Upvotes: 2

Related Questions