2

I have this regex:

  const str = '1.22.333'; 
  const patt = /^(?:\d+\.?)+(?<!\.)$/;
  const result = str.match(patt);

It only works in Chrome. In Firefox I get:

SyntaxError: invalid regexp group

https://jsbin.com/colehogema/edit?html,js,output

Is there any other way of writing this regex so other browsers can run it?

Requirements:

  • Start with number
  • End with number
  • Numbers separated with one dot
  • Only a single number with no dots is valid
mrzasa
  • 22,895
  • 11
  • 56
  • 94
Joe
  • 4,274
  • 32
  • 95
  • 175

2 Answers2

2

You can use normal repetition without any lookarounds:

  const str = '1.22.333'; 
  const patt = /^(?:\d+\.)*\d+$/;
  const result = str.match(patt);
  console.log(result);

See Demo

Explanation:

  • you match digits ending with a dot with \d+\., .e.g 123.
  • you repeat this zero or more times: 123.32.12.
  • at the end you match just digits: \d+

I've discussed thoroughly matching digits with separators in a blogpost about regex performance. It's worth noting that your initial regex was prone to catastrophic backtracking in (?:\d+\.?)+ part.

As a VLAZ noted, negative lookbehinds ((?<!\.)) are only supported by chrome. More about lookarounds in JS: Javascript: negative lookbehind equivalent?

mrzasa
  • 22,895
  • 11
  • 56
  • 94
0
/^(?:(?:\d+\.){2})?\d+$/

This matches either three numbers separated by two dots or a number. If the count of numbers separated by dots can be anything then the regex will be :

/^(?:\d+\.)*\d+$/

as answered by @mrzasa here.

Regex explanation can be found here

const str = '1.22.333'; 
const patt = /^(?:(?:\d+\.){2})?\d+$/;
const result = str.match(patt);
console.log(result);
rprakash
  • 500
  • 5
  • 10