Shota
Shota

Reputation: 7340

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

Upvotes: 6

Views: 1323

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627126

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.

Upvotes: 16

Related Questions