../courses.php
RegEx
REGEX107
3
Group Parts And Choose Alternatives
Groups let you treat pattern parts together, and choices let one pattern accept alternatives.
Why do RegEx patterns use groups?
Groups organize pattern parts so they can be repeated, captured, or used with alternatives.
Parentheses create groups in RegEx.
A group lets several characters behave like one pattern part.
The vertical bar means OR.
Together, groups and choices can match controlled alternatives.
Groups are useful, but they can make a pattern harder to read if overused.
Matching one of several words
const text = "The pet is a dog.";
console.log(/cat|dog/.test(text)); // true
console.log(/(cat|dog)/.test(text)); // true
console.log(/^(cat|dog)$/.test("dog")); // true
console.log(/^(cat|dog)$/.test("dogma")); // false
| means OR.
cat|dog means cat or dog.
(cat|dog) groups the choice.
Anchors can make the whole value be only cat or dog.
Groups make the structure of the pattern clearer.
Alternatives
Choices allow one approved option from a list.
Structure
Groups organize pattern parts.
Reuse
A grouped part can be repeated as a unit.
Extraction
Capturing groups can pull out matched pieces.
Choice too loose
Grouped and anchored choice
Ask ChatGPT: "Are my RegEx alternatives grouped correctly, and should the whole input be anchored?"
Write a pattern that matches cat or dog.
Add anchors so only cat or dog is allowed.
Test dog.
Test dogma.
Explain what the vertical bar means.
Forgetting that | means OR.
Using choices without grouping when grouping would clarify meaning.
Letting partial words pass.
Creating a long unreadable list inside one pattern.
Using RegEx when a normal allowed-list check would be simpler.
Use groups and choices to match controlled alternatives.
Login - Jit4All
Login
Welcome back to Jit4All