RX

Anchors & Boundaries

Regular Expressions · 6 entries

^ Start Anchor

syntax
^pattern
example
JS:  /^#!/.test('#!/bin/bash')    // true
JS:  /^#!/.test('echo #!/bin')   // false
Py:  bool(re.match(r'^#!', '#!/usr/bin/env python'))  # True
output
true, false, True

Note Without the m flag, ^ matches only the very beginning of the entire string. With the m flag, it matches the start of each line (after every newline character).

$ End Anchor

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

Note Without the m flag, $ matches the very end of the string (or before a trailing newline in Python). With m, it matches the end of each line.

\b Word Boundary (Detail)

syntax
\b  matches the boundary between \w and \W (or string start/end)
example
JS:  'reinvent invent invention'.match(/\binvent\b/g)
Py:  re.findall(r'\binvent\b', 'reinvent invent invention')
output
["invent"]  (only the standalone word)

Note A word boundary exists at three positions: before the first \w character, after the last \w character, and between a \w and \W character. It does NOT match any characters itself -- it matches a position.

\A Absolute Start of String (Python)

syntax
\A  matches the very start of the string (ignores multiline)
example
Py:  re.search(r'\AFirst', 'First line\nSecond line', re.MULTILINE)
     # Matches 'First'
Py:  re.search(r'^Second', 'First line\nSecond line', re.MULTILINE)
     # Also matches (^ respects multiline)
output
\A always means absolute start, even with re.MULTILINE

Note \A is not available in JavaScript. It is equivalent to ^ when multiline mode is off, but unlike ^, it never changes behavior with the m flag. Use \A in Python when you always mean the beginning of the entire string.

\Z Absolute End of String (Python)

syntax
\Z  matches the very end of the string (ignores multiline)
example
Py:  re.search(r'end\Z', 'start\nmiddle\nend')
     # Matches 'end'
Py:  re.search(r'middle$', 'start\nmiddle\nend', re.MULTILINE)
     # Also matches ($ respects multiline)
output
\Z matches only the absolute end, regardless of flags

Note In Python, \Z matches the absolute end (after the last character). Note: \z (lowercase) is used in some other flavors (Ruby, PCRE) for the same purpose, while Python's \Z (uppercase) does not match before a trailing newline. Not available in JavaScript.

Multiline Behavior with ^/$

syntax
Use m flag to make ^ and $ match line boundaries
example
JS:  'line1\nline2\nline3'.match(/^\w+/gm)
Py:  re.findall(r'^\w+', 'line1\nline2\nline3', re.MULTILINE)
output
["line1", "line2", "line3"]  (each line start matched)

Note Without the m flag, only 'line1' would match ^\w+. A common mistake is forgetting the m flag when processing multi-line text like log files or configuration files. In Python, re.MULTILINE or re.M is the flag; in JS, use /m.