Learn regular expressions · Lesson 7
Groups and alternation
Alternation: |
A vertical bar means “or”: cat|dog matches either.
/cat|dog/g2 matchesA cat, a dog, a cow.Try it in Dotstar →
The bar has the lowest precedence of anything in a pattern: it splits the whole pattern, or the whole group it’s in, in two. So ^cat|dog$ isn’t “cat or dog, alone”: it’s ^cat or dog$, and matches the start of “category”:
/^cat|dog$/1 matchcategoryTry it in Dotstar →
Parentheses group
To limit an alternation, put it in a group. (?:…) is a group that only groups:
/^(?:cat|dog)$/No matchescategoryTry it in Dotstar →
Now it has to be all of the text, so there’s no match; with the text dog, there would be.
A group is also one item to a quantifier. (?:ha)+ is ha, once or more; without the group, ha+ would be an h and then a’s:
/(?:ha)+/g4 matchesha haha hahaha haaaTry it in Dotstar →
Plain parentheses capture
Plain parentheses, (…), group too, and also capture: they remember the text they matched, so you can use it afterwards, in code or a replacement. (?:…) is the same without the remembering. The next lesson is about captures; until then, (?:…) when you only need to group keeps the numbering of the others simple.
Which alternative wins
When more than one alternative could match at the same place, most engines take the first one that leads to a match, reading left to right; not the longest. cat|category matches only “cat” in “category”:
/cat|category/1 matchcategoryTry it in Dotstar →
Put the longer one first, category|cat, or make the pattern say what follows: cat(?:egory)?.