It's just regex really slow, why?
I wrote this very simple regex that checks if the entire string contains one or more hexadecimal numbers (optionally starting with "0x", separated by comma, minus sign, or space character):
/^((0x)?[0-9A-F]+[,\-\s]*)+$/i
For me this regex is very simple, but this simple test completely ruins Firefox and Edge, Chrome uses 100% CPU usage for about 15 seconds and then returns the expected result "false":
/^((0x)?[0-9A-F]+[,\-\s]*)+$/i.test("012345678901234567890123456789_0");
Does anyone know what is wrong here?
+3
source to share
1 answer
This is a common case of a catastrophic rollback (see your regex demo ) where a group contains two subpatterns, one of which is optional.
You need to regroup the template as
/^(?:0x)?[0-9A-F]+(?:[,\s-]+(?:0x)?[0-9A-F]+)*$/i
It will now match:
-
^
- beginning of line -
(?:0x)?[0-9A-F]+
- hexadecimal number -
(?:[,\s-]+(?:0x)?[0-9A-F]+)*
- zero or more sequence-
[,\s-]+
- 1 + space,,
or-
characters (remove+
only 1 if needed) -
(?:0x)?[0-9A-F]+
- hexadecimal number
-
-
$
- end of line.
See regex demo .
+3
source to share