RX

String Operations with Regex

Regular Expressions · 10 entries

JS: test() - Boolean Check

syntax
/pattern/.test(string)  =>  boolean
example
const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test('[email protected]');
console.log(isEmail);
output
true

Note Returns true/false. The fastest way to check if a pattern matches. Warning: when using test() with the g flag, the regex remembers lastIndex between calls, which can cause alternating true/false results. Avoid g with test() or reset lastIndex = 0.

JS: match() - Find Matches

syntax
string.match(/pattern/)  or  string.match(/pattern/g)
example
// Without g: returns first match + groups
'Price: $42.99'.match(/(\$)(\d+\.\d{2})/)
// With g: returns all matches (no groups)
'$42.99 and $18.50'.match(/\$\d+\.\d{2}/g)
output
Without g: ["$42.99", "$", "42.99"]
With g: ["$42.99", "$18.50"]

Note Behavior changes completely depending on the g flag. Without g, you get detailed info (groups, index). With g, you get a flat array of all matches but lose group details. Use matchAll for both multiple matches AND group info.

JS: matchAll() - Iterate All Matches

syntax
string.matchAll(/pattern/g)  =>  iterator of match objects
example
const text = 'dates: 2026-04-04, 2025-12-25';
for (const m of text.matchAll(/(\d{4})-(\d{2})-(\d{2})/g)) {
  console.log(m[0], '=> year:', m[1]);
}
output
"2026-04-04 => year: 2026"
"2025-12-25 => year: 2025"

Note Returns an iterator, so use for...of or [...spread]. Requires the g flag or it throws an error. This is the modern replacement for the while(exec()) loop pattern.

JS: replace() / replaceAll()

syntax
string.replace(/pattern/, replacement)
string.replaceAll(/pattern/g, replacement)
example
// Backreference in replacement
'John Smith'.replace(/(\w+) (\w+)/, '$2, $1')
// Function replacement
'hello'.replace(/\w/g, c => c.toUpperCase())
output
"Smith, John"
"HELLO"

Note In the replacement string, $1 $2 refer to captured groups, $& is the full match, $` is before-match, $' is after-match. Use a function for dynamic replacements. replaceAll() requires the g flag on regex arguments.

JS: split() with Regex

syntax
string.split(/pattern/)
example
'one, two;  three|four'.split(/[,;|]\s*/)
output
["one", "two", "three", "four"]

Note Split accepts a regex as the separator. If the regex contains capturing groups, the captured text is included in the result array. This can be surprising -- use non-capturing groups (?:) if you don't want separator parts in the output.

JS: exec() - Detailed Match

syntax
regex.exec(string)  =>  match object or null
example
const re = /(?<word>\w+)/g;
let m;
while ((m = re.exec('hello world')) !== null) {
  console.log(`Found "${m[0]}" at index ${m.index}`);
}
output
"Found \"hello\" at index 0"
"Found \"world\" at index 6"

Note Returns one match at a time with full detail (groups, index, named groups). With the g flag, successive calls advance through the string via lastIndex. Modern code should prefer matchAll() over the exec() while loop.

Python: re.search() - First Match

syntax
re.search(pattern, string)  =>  Match object or None
example
import re
m = re.search(r'(\d+)\s*(kg|lb)', 'Weight: 75 kg')
if m:
    print(m.group(0), m.group(1), m.group(2))
output
"75 kg" "75" "kg"

Note Scans the entire string and returns the first match. Use re.match() if you only want to check the beginning of the string. Always check for None before calling .group() to avoid AttributeError.

Python: re.findall() - All Matches

syntax
re.findall(pattern, string)  =>  list of strings or tuples
example
import re
re.findall(r'\b[A-Z][a-z]+\b', 'Alice met Bob in Paris')
output
["Alice", "Bob", "Paris"]

Note Returns a list of all non-overlapping matches. If the pattern has groups, findall returns a list of groups (or tuples for multiple groups) instead of the full match. Use (?:) for groups you don't want captured in the result.

Python: re.sub() - Replace

syntax
re.sub(pattern, replacement, string, count=0)
example
import re
# Backreference replacement
re.sub(r'(\w+) (\w+)', r'\2, \1', 'John Smith')
# Function replacement
re.sub(r'\d+', lambda m: str(int(m.group()) * 2), 'a3 b5')
output
"Smith, John"
"a6 b10"

Note In the replacement, \1 or \g<1> references group 1, \g<name> references named groups. Pass a function as replacement for dynamic logic. Use count=1 to replace only the first occurrence (similar to omitting the g flag in JS).

Python: re.split() - Split by Pattern

syntax
re.split(pattern, string, maxsplit=0)
example
import re
re.split(r'[,;]\s*', 'apples, oranges; bananas,  grapes')
output
["apples", "oranges", "bananas", "grapes"]

Note Like JS split, captured groups are included in the result. Empty matches at the start or end of the string produce empty strings in the output list. Use maxsplit to limit the number of splits.