Regex Cheat Sheet with Python and JavaScript Examples
Whether validating user email addresses, sanitizing log files, extracting URLs from messy text corpora, or refactoring code via global search-and-replace, Regular Expressions (Regex) are an indispensable tool for every software engineer. Despite their reputation for looking cryptic and intimidating at first glance, regular expressions are simply formal patterns used to match character combinations in strings.
This comprehensive cheat sheet covers essential regex syntax rules, quantifiers, anchors, and practical implementation examples in both Python and JavaScript.
1. Core Syntax and Character Classes
Character classes allow you to match specific sets or categories of characters within a target string.
- .: Matches any single character except newline.
- \d: Matches any digit (equivalent to [0-9]).
- \D: Matches any non-digit character (equivalent to [^0-9]).
- \w: Matches any word character (alphanumeric + underscore, equivalent to [a-zA-Z0-9_]).
- \W: Matches any non-word character.
- \s: Matches any whitespace character (spaces, tabs, newlines).
- \S: Matches any non-whitespace character.
2. Anchors and Quantifiers
Anchors specify positions within a string, while quantifiers control how many times a preceding character or group must repeat.
- ^: Asserts the start of a string or line.
- $: Asserts the end of a string or line.
- *: Matches 0 or more times.
- +: Matches 1 or more times.
- ?: Matches 0 or 1 time (optional).
- {n}: Matches exactly $n$ times.
- {n,}: Matches $n$ or more times.
- {n,m}: Matches between $n$ and $m$ times.
3. Regular Expressions in Python (re module)
Python provides built-in regex support via the re module, offering functions like re.search(), re.findall(), and re.sub().
import re
# 1. Validate an email address format
email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
test_email = "developer@codecrown.in"
if re.match(email_pattern, test_email):
print("Valid email address!")
# 2. Extract all numbers from a text log
log_text = "Error 404: Page not found on server port 8080."
numbers = re.findall(r'\d+', log_text)
print(numbers) # Output: ['404', '8080']
# 3. Search and replace sensitive data
sensitive_str = "My phone number is 555-0199."
sanitized = re.sub(r'\d{3}-\d{4}', 'REDACTED', sensitive_str)
print(sanitized) # Output: My phone number is REDACTED.
4. Regular Expressions in JavaScript
JavaScript supports regex natively using regular expression literals (/pattern/flags) or the RegExp object, working alongside string methods like .test(), .match(), and .replace().
// 1. Test for URL protocol validation
const urlPattern = /^https?:\/\/[\w\-]+(\.[\w\-]+)+[/#?]?.*$/;
const targetUrl = "https://codecrown.in/tutorials";
console.log(urlPattern.test(targetUrl)); // Output: true
// 2. Extract matching capture groups
const dateString = "Today's date is 2026-10-19";
const dateRegex = /(\d{4})-(\d{2})-(\d{2})/;
const match = dateString.match(dateRegex);
if (match) {
console.log(`Year: ${match[1]}, Month: ${match[2]}, Day: ${match[3]}`);
// Output: Year: 2026, Month: 10, Day: 19
}
// 3. String replacement with global flag
const messyText = "apple, banana; orange:grape";
const cleanText = messyText.replace(/[,;:]/g, "-");
console.log(cleanText); // Output: apple- banana- orange-grape
Conclusion
Mastering regular expressions equips developers with a powerful pattern-matching language that transcends individual programming languages. Whether validating inputs in Python or parsing text streams in JavaScript, regex streamlines complex string manipulation tasks efficiently.