1

First of all, sorry for the unclear title, it's hard to describe (and to find an existing solution for the same reason).

I use this regex in Javascript, to collect numbers in a string :

/(?:^|[^\d])([\d]+)(?:$|[^\d])/g

Executing it on "5358..2145" returns 2 matches, where the submatches are "5358" and "2145"

But if I use it on "5358.2145", I receive only 1 match : "5358"

So, I understand it so :

  • The first match is found ("5358.") so the point goes in the first match
  • What I want as second match is not preceded with start of string or the point because this point already belongs to the first match

How can I change my pattern to find all numbers separated with 1 non-number character ?

Alsatian
  • 3,086
  • 4
  • 25
  • 40

1 Answers1

1

Use a negative lookahead at the end:

/(?:^|\D)(\d+)(?!\d)/g

See the regex demo

The pattern matches:

  • (?:^|\D) - either start of string (^) or any non-digit char (\D)
  • (\d+) - Group 1: one or more digits
  • (?!\d) - the negative lookahead failing the match if there is a digit immediately to the right of the current location.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • You can see [another answer of mine](http://stackoverflow.com/questions/31201690/find-word-not-followed-by/31201710#31201710) to see how negative lookaheads work. – Wiktor Stribiżew Apr 13 '17 at 13:44