RX

Basic Patterns

Regular Expressions · 7 entries

Literal Match

syntax
/hello/  or  r'hello'
example
JS:  'say hello world'.match(/hello/)
Py:  re.search(r'hello', 'say hello world')
output
Matches "hello" at index 4

Note Characters that are not special match themselves exactly. Regex is case-sensitive by default -- use the i flag for case-insensitive matching.

Dot (Any Character)

syntax
.  (matches any single character except newline)
example
JS:  'bat bet bit'.match(/b.t/g)
Py:  re.findall(r'b.t', 'bat bet bit')
output
["bat", "bet", "bit"]

Note The dot does NOT match newline (\n) by default. Use the s (dotall) flag to make dot match newline as well. A common beginner mistake is using . when you mean a literal period -- escape it as \. instead.

^ Start of String

syntax
^pattern
example
JS:  /^Error/.test('Error: file missing')   // true
JS:  /^Error/.test('An Error occurred')   // false
Py:  bool(re.match(r'^Error', 'Error: file missing'))  # True
output
true, false, True

Note Matches position at start of string. With the m (multiline) flag, ^ matches the start of each line instead. Do not confuse this with [^...] inside a character class, which means negation.

$ End of String

syntax
pattern$
example
JS:  /\.json$/.test('config.json')   // true
JS:  /\.json$/.test('config.json.bak')  // false
Py:  bool(re.search(r'\.json$', 'config.json'))  # True
output
true, false, True

Note Matches position at end of string. With the m flag, $ matches the end of each line. In Python, re.match only checks the start -- use re.search with $ to check the end.

\b Word Boundary

syntax
\bword\b
example
JS:  'catfish is not a cat'.match(/\bcat\b/g)
Py:  re.findall(r'\bcat\b', 'catfish is not a cat')
output
["cat"]  (matches only the standalone word, not "catfish")

Note A word boundary is the position between a word character (\w) and a non-word character. Essential for whole-word searches. In JS, remember to double-escape in strings: new RegExp('\\bcat\\b').

\B Non-Word Boundary

syntax
\Bpattern  or  pattern\B
example
JS:  'catfish is not a cat'.match(/\Bcat/g)
Py:  re.findall(r'\Bcat', 'catfish is not a cat')
output
[]  (no match -- 'cat' always starts at a word boundary here)

'scattered'.match(/\Bcat\B/g) => ["cat"]  (inside a word)

Note \B matches every position that is NOT a word boundary -- useful for finding substrings embedded within larger words.

Escaping Special Characters

syntax
\. \* \+ \? \( \) \[ \] \{ \} \^ \$ \| \\
example
JS:  'Price: $9.99'.match(/\$\d+\.\d{2}/)
Py:  re.search(r'\$\d+\.\d{2}', 'Price: $9.99')
output
"$9.99"

Note All special regex characters must be escaped with a backslash to match literally. The special characters are: . * + ? ( ) [ ] { } ^ $ | \. In Python raw strings (r'...'), you only escape for regex, not for Python itself.