Learn regular expressions by seeing patterns, test cases, and match results side-by-side
Match specific sets of characters using character classes and ranges
Square brackets [] define a character class that matches any one character inside the brackets.
Pattern breakdown:
[aeiou] - matches any single vowelIn "apple", this matches 'a', then 'e'. In "rhythm", there are no vowels so no matches occur.
apple banana cherry rhythm
Character ranges use a hyphen to specify a range of characters. [0-9] matches any digit.
Pattern breakdown:
[0-9]+ - one or more digitsThis finds "3", "2", "2024", "555", and "1234" in the test input.
Source: Python re Documentation
I have 3 cats and 2 dogs. The year 2024 was great. No numbers here! Call me at 555-1234.
A caret ^ at the start of a character class negates it, matching any character NOT in the class.
Pattern breakdown:
[^0-9]+ - one or more characters that are NOT digitsThis matches "abc", "def", "test", and "data" - all the non-numeric parts.
Source: Regular-Expressions.info - Negated Character Classes
abc123def 456 test789data
Shorthand character classes provide convenient shortcuts for common patterns.
Common shorthands:
\w - word character [a-zA-Z0-9_]\d - digit [0-9]\s - whitespace [ \t\n\r\f\v]\W, \D, \S - negated versionsThe pattern \w+ matches sequences of word characters: "Hello", "World", "test_variable_123", "price", "49", "99".
Source: Python re Syntax Documentation
Hello World! test_variable_123 price: $49.99