Regular expressions are a powerful tool for pattern matching in strings, and understanding character classes, quantifiers, anchors, and alternation is fundamental to harnessing their power. Character classes are like shortcuts that let you match any single character from a specified set. For example, \d matches any digit (0-9), \w matches any word character (alphanumeric plus underscore), and [aeiou] matches any vowel. These are essential for making your patterns flexible without listing every possibility. When you need to match one of several entire patterns (not just single characters), you use alternation with the | (OR) operator, such as (USD|EUR|GBP) to match any of those three currency codes.
Key Takeaways
- Character classes (e.g.,
\d,[a-z]) match any single character from a defined set. - Alternation (
|) matches one of several complete patterns (e.g.,(cat|dog)). - Quantifiers (e.g.,
+,*,?,{n,m}) define how many times a preceding element repeats. - Anchors (e.g.,
^,$,\b) match positions in a string, ensuring precise location-based matches. - Combine these concepts to build robust regex for tasks like input validation, parsing, and text manipulation.
Code Example
How this code works
The validatePassword function determines if a given password string meets specific security criteria using a regular expression. Its core is the passwordRegex pattern. This pattern begins with ^ and ends with $, which are anchors ensuring the entire string must match the rules from start to finish. Crucially, it uses three "positive lookaheads": (?=.*\d), (?=.*[a-z]), and (?=.*[A-Z]). These lookaheads ensure the password contains at least one digit, one lowercase letter, and one uppercase letter, respectively. A subtle point here is that these lookaheads check for conditions (like "is there a digit somewhere?") without "consuming" characters from the string, allowing the main part of the regex to then match the string from the very beginning.
After the lookaheads establish the required character types, the [a-zA-Z0-9!@#$%^&*-] part defines the only characters allowed in the password. This character class permits uppercase and lowercase letters, digits, and a specific set of special characters. The quantifier {8,15} immediately following specifies that the allowed characters must appear between 8 and 15 times, enforcing the password length. Finally, passwordRegex.test(password) evaluates if the input password string successfully matches all these combined rules, returning true or false.