Regular Expressions (Regex)
Regular Expressions (Regex) are sequences of characters that define a search pattern. They are extremely powerful for text processing, validation (like checking emails), and string manipulation.
1. Basic Syntax
.: Matches any single character (except newline).^: Anchors to the start of the string.$: Anchors to the end of the string.|: Acts as a logical OR (e.g.,cat|dogmatches "cat" or "dog").\: Escapes special characters (e.g.,\.matches a literal dot).
2. Character Sets & Classes
[abc]: Matches any one character inside the brackets (a, b, or c).[^abc]: Matches any character NOT inside the brackets.[a-z]: Matches any lowercase letter.
Shorthand Classes
\d: Any digit (0-9).\w: Any word character (a-z, A-Z, 0-9, _).\s: Any whitespace (space, tab, newline).\D,\W,\S: The inverse (non-digit, non-word, non-whitespace).
3. Quantifiers
Quantifiers specify how many times the preceding element should match.
*: 0 or more times.+: 1 or more times.?: 0 or 1 time (optional).{3}: Exactly 3 times.{2,5}: Between 2 and 5 times.
4. Groups and Capturing
(abc): Groups characters together. Also captures the match for later use.(?:abc): Non-capturing group (groups but doesn't save the match).
5. Usage in Languages
JavaScript
In JS, regex literals are written between slashes /pattern/flags.
const emailPattern = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
const email = "test@example.com";
if (emailPattern.test(email)) {
console.log("Valid email");
}
const text = "The year is 2023";
const year = text.match(/\d{4}/); // ["2023"]
Python
Python uses the re module.
import re
text = "The price is $99"
match = re.search(r'\$(\d+)', text)
if match:
print(match.group(1)) # Output: 99