JavaScript
JavaScript has built-in support for regular expressions using the RegExp object or literal syntax /.../.
const text = "Contact us at [email protected] or [email protected].";
const pattern = /([a-zA-Z0-9._-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/g;
// 1. Check if it matches
const isValid = pattern.test(text);
console.log("Has email?", isValid);
// 2. Get all matches
const matches = text.match(pattern);
console.log("Matches:", matches);
// 3. Extract capture groups
let match;
// Reset lastIndex since we are reusing a global pattern
pattern.lastIndex = 0;
while ((match = pattern.exec(text)) !== null) {
console.log("Found: " + match[0]);
console.log("User: " + match[1] + ", Domain: " + match[2]);
}
Python
Python uses the built-in re module. Use raw strings r"..." to avoid escaping backslashes.
import re
text = "Contact us at [email protected] or [email protected]."
pattern = r"([a-zA-Z0-9._-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})"
# 1. Check if it matches (search finds the first match anywhere)
if re.search(pattern, text):
print("Has email: True")
# 2. Get all matches (returns list of tuples if there are capture groups)
matches = re.findall(pattern, text)
print("Matches:", matches)
# 3. Extract capture groups
for match in re.finditer(pattern, text):
print(f"Found: {match.group(0)}")
print(f"User: {match.group(1)}, Domain: {match.group(2)}")
PHP
PHP uses PCRE (Perl Compatible Regular Expressions) functions like preg_match and preg_match_all.
<?php
$text = "Contact us at [email protected] or [email protected].";
$pattern = "/([a-zA-Z0-9._-]+)@([a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4})/";
// 1. Check if it matches
if (preg_match($pattern, $text)) {
echo "Has email: True\n";
}
// 2. Get all matches and capture groups
// PREG_SET_ORDER groups results by each match
if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
echo "Found: " . $match[0] . "\n";
echo "User: " . $match[1] . ", Domain: " . $match[2] . "\n";
}
}
?>