Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webstorm Javascript Regex - Single character alternation in regex

I am trying to split the string based on two separators like this:

"some-str_to_split".split(/-|_/)

So it should split the string based on "-" and "_". It works fine, but Webstorming giving a warning:

Single character alternation in regex

like image 647
Shota Avatar asked Dec 13 '22 19:12

Shota


1 Answers

Note that -|_ is a patter that matches - or _, but each time the regex engine sumbles upon a position in the string, the - is tested against first, and if it is not matched, _ is tried. That involves the so-called backtracking. When you use [-_], a so called character class, a regex engine uses a compiled mini-program that performs the search faster eliminating the backtracking mechanism.

Thus, the warning is just a kind of a hint for you that your pattern can be enhanced. In case there are 2 chars, the difference in performance is negligeable, if there are 100+ alternatives, the difference will be more tangible.

like image 162
Wiktor Stribiżew Avatar answered Dec 17 '22 22:12

Wiktor Stribiżew