3

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

  • the string starts
  • there are 0 or more non-digit characters
  • then 1 or more digits (which we capture)
  • that pattern repeats until the end of the string

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?

user1775718
  • 1,499
  • 2
  • 19
  • 32

1 Answers1

2

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Hello sir, for condition `BUT only if the string ends with numbers.` just for my knowledge how are we fulfilling it? Thank you sir – RavinderSingh13 Jan 12 '23 at 13:10
  • 1
    We have a lookahead assertion here `(?=(?:\w+\d)?\b)` that is making sure that we have a digit just before word boundary after matching 1 or more word characters. – anubhava Jan 12 '23 at 14:17