basil basil - 2 months ago 17
Perl Question

Matching numbers with non-digits embedded

I am trying to match strings of digits that contain non-digits within them. Using the default text in http://regexr.com/, the following should match:

v2.1
-98.7
3.141
.6180
9,000
+42
555.123.4567
+1-(800)-555-2468


The following should not match:

0123456789
12345


I tried:

/[^\n\ ]{1,}\d+\S+\d/g


But it would not match
+42
and it incorrectly matched
0123456789
and
12345
, and it treated
"555.123.4567 +1-(800)-555-2468"
as one string.

I tried to alleviate it by putting a
$
at the end but that matched nothing. Not sure what I am doing wrong.

Answer

You can use this regex to match any text with at least one non-digit:

/^\d*[^\d\n]+\d.*$/mg

RegEx Demo

RegEx Breakup:

  • ^ - Start
  • \d* - Match 0 or more digits
  • [^\d\n]+ - Match 1 or more of any character that is not a digit and not a newline
  • \d - Match a digit
  • .* - Match 0 or more of any character
  • $ - End
Comments