JavaScript RegExp (x|y) Expression
The (x|y) expression in JavaScript regular expressions is used to match either x or y. It acts as an OR operator in regular expressions, allowing you to specify multiple patterns to match.
let regex = /(cat|dog)/g;
let str = "I have a cat and a dog.";
let matches = str.match(regex);
console.log(matches);
Output
[ 'cat', 'dog' ]
The pattern (cat|dog) matches either cat or dog in the string.
Syntax:
/(x|y)/
- Matches either x or y.
- x and y can be characters, words, or even complex patterns.
Key Points
- The (x|y) expression works as an alternation operator to match one of the given patterns.
- Can be used to match characters, words, or sub-patterns.
- Useful in scenarios where multiple possibilities exist for a match.
Real-World Examples
1. Matching Either Word
let regex = /(red|blue)/g;
let str = "The flag is red and blue.";
let matches = str.match(regex);
console.log(matches);
Output
[ 'red', 'blue' ]
Here, (red|blue) matches either “red” or “blue”.
2. Matching Single Characters
let regex = /(a|e|i|o|u)/g;
// Matches any vowel
let str = "hello world";
let matches = str.match(regex);
console.log(matches);
Output
[ 'e', 'o', 'o' ]
The pattern (a|e|i|o|u) matches any vowel in the string.
3. Using Alternation with Complex Patterns
let regex = /(Mr\.|Mrs\.|Ms\.)\s[A-Z][a-z]+/g;
let str = "Mr. Smith and Mrs. Johnson are here.";
let matches = str.match(regex);
console.log(matches);
Output
[ 'Mr. Smith', 'Mrs. Johnson' ]
The (Mr\.|Mrs\.|Ms\.) pattern matches formal titles followed by a capitalized last name.
4. Validating Input with Multiple Options
let regex = /^(yes|no|maybe)$/;
let input = "yes";
if (regex.test(input)) {
console.log("Valid input.");
} else {
console.log("Invalid input.");
}
Output
Valid input.
Here, the pattern ^(yes|no|maybe)$ ensures the input is either “yes”, “no”, or “maybe”.
5. Matching File Extensions
let regex = /\.(jpg|png|gif)$/;
let filename = "picture.png";
if (regex.test(filename)) {
console.log("Valid image file.");
} else {
console.log("Invalid file format.");
}
Output
Valid image file.
The (jpg|png|gif) pattern matches specific file extensions.
Common Patterns Using (x|y)
- Match Multiple Words:
/(apple|banana|cherry)/g
- Match Optional Titles:
/(Dr\.|Mr\.|Ms\.)\s[A-Z][a-z]+/
- Match Either of Two Numbers:
/(123|456)/g
- Match Optional Characters:
/colou?r/ // Matches "color" or "colour"
Why Use (x|y)?
- Flexible Matching: Allows checking for multiple options in one pattern.
- Improved Readability: Simplifies patterns by combining alternatives into a single expression.
- Versatility: Works for both simple characters and complex sub-patterns.
Conclusion
The (x|y) expression is a powerful tool for defining alternatives in JavaScript regular expressions, making it invaluable for text validation, parsing, and extraction.
Recommended Links:
- JavaScript RegExp Complete Reference
- JavaScript Cheat Sheet-A Basic guide to JavaScript
- JavaScript Tutorial