ms icon indicating copy to clipboard operation
ms copied to clipboard

Useless non capturing group in regex

Open Haltarys opened this issue 4 years ago • 2 comments

 var match = /^(-?(?:\d+)?\.?\d+)

Could simply be replaced with:

  var match = /^(-?\d*\.?\d+)

The \d+ matches a digit one or more times. This match is then matched 0 or 1 time with the second ? in (?:\d+)?. This whole sub-regex could simply be expressed as \d* to match a digit 0 or more times.

Haltarys avatar Aug 21 '21 19:08 Haltarys

I doubt that it is equivalent to the original regex. non-capturing group means, that the group has to exist but is not in the resulting match. So the original regex expects atleast a number value before the dot. Your simplification says, that it can be also no digit at all before the dot.

Uzlopak avatar Mar 06 '22 12:03 Uzlopak

(?:\d+)? == \d* is what I'm saying.

Haltarys avatar Mar 06 '22 19:03 Haltarys