Anchors and Word Boundaries

`^ $ \A \z \Z \b \B`: how multiline mode changes `^` and `$`, why `$` accepts a trailing newline in Python and PCRE2, which engines have `\A`, `\z` and `\Z`, and what `\b` means for non-ASCII text.

The problem

Validators and extractors depend on where a match may begin and end. `^\d+$` accepts `"12\n"` in Python and PCRE2 but rejects it in Go and JavaScript, and `caf\b` is a boundary inside `café` in Go and JavaScript but not in Python. Anchors are zero-width, so a mistake changes where the match lands rather than what it contains, and tests with clean input never notice.

How it works

  • Without flags, `^` is the start of the input and `$` is the end of the input. Go and JavaScript treat only the very end as `$`; Python and PCRE2 also let `$` match just before a final `\n`. Observed for `^\d+$` on `12\n`: Go no match, JavaScript no match, Python matches `12`, PCRE2 10.42 (default options) matches `12`.
  • `grep -P` sets PCRE2's DOLLAR_ENDONLY, so it behaves like Go here: `printf '12\n' | grep -zcP '^\d+$'` prints `0`, while `^\d+\Z` prints `1`. The PCRE2 column on this sheet is the library with default options, not `grep -P`.
  • Absolute anchors: `\A` is the start in Go, Python and PCRE2 (in JavaScript it is an identity escape that matches the letter `A`). `\z` is the absolute end in Go and PCRE2; Python 3.13 rejects it (`bad escape \z at position 3`). `\Z` means "end, or before a final newline" in Python and PCRE2 and is a compile error in Go (`invalid escape sequence: `\Z``).
  • Portable "whole string" checks: Python `re.fullmatch`, Go and JavaScript `^...$` without the `m` flag, PCRE2 `\A...\z`. `re.fullmatch(r"\d+", "12\n")` is `None`, `re.search(r"^\d+$", "12\n")` is a match.
  • Multiline mode (`m`) makes `^` and `$` also match at line breaks: `^\d+$` on `12\n\n` matches in all four only with `m`. `$` on `a\n` finds positions 1 and 2 with `m` everywhere; without `m`, Python still finds both (1 and 2) while Go and JavaScript find only 2.
  • What counts as a line break differs: Go, Python and PCRE2 (LF build) use `\n` only; JavaScript also uses `\r`, U+2028 and U+2029. With `m`, `a$` matches in `a\r\nb` and `^b` matches in `a\rb` only in JavaScript.
  • `\b` sits between a word and a non-word character (or an edge); `\B` is its negation; neither consumes a character. Because `\w` is ASCII in Go, JavaScript and PCRE2, `caf\b` matches inside `café` there; in Python `\b` is Unicode-aware and `caf\b` does not match. JavaScript's `u` flag does not change `\b` (`/\bé/u` on `é` is false); PCRE2 gets Unicode word boundaries from `(*UTF)(*UCP)`; Go has no switch.
  • Empty input: `\b` never matches the empty string; `\B` matches it in Go, JavaScript and PCRE2, but `re.search(r"\B", "")` is `None` on Python 3.13. A `^` or `$` in the middle (`a^b`, `a$b`) never matches, even with `m`.

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    digits := regexp.MustCompile(`^\d+$`)
    fmt.Println(digits.MatchString("12"), digits.MatchString("12\n"))
    lines := regexp.MustCompile(`(?m)^\d+$`)
    fmt.Println(lines.FindAllString("12\n34\n", -1))
    whole := regexp.MustCompile(`\A\d+\z`)
    fmt.Println(whole.MatchString("12\n"))
    _, err := regexp.Compile(`\d+\Z`)
    fmt.Println(err)
    word := regexp.MustCompile(`caf\b`)
    fmt.Println(word.MatchString("café"))
}

// Output on Go 1.24:
// true false
// [12 34]
// false
// error parsing regexp: invalid escape sequence: `\Z`
// true

Python: `$` accepts a trailing newline, `fullmatch` and `\Z` do not, `\b` is Unicode-aware, `\z` is rejected on 3.13.

Python
import re

print(bool(re.search(r"^\d+$", "12\n")))
print(bool(re.fullmatch(r"\d+", "12\n")))
print(bool(re.search(r"^\d+\Z", "12\n")))
print(bool(re.search(r"\bcaf\b", "café")))
print(re.findall(r"^\w+$", "ab\ncd\n", re.M))
try:
    re.compile(r"\d+\z")
except re.error as e:
    print(e)

# Output on Python 3.13:
# True
# False
# False
# False
# ['ab', 'cd']
# bad escape \z at position 3

JavaScript: `$` is strict, `m` also splits on `\r`, `\b` is ASCII-only even with `u`, and `\A`/`\z` do not exist (they match the letters `A` and `z`).

javascript
console.log(/^\d+$/.test("12\n"));
console.log(/^\d+$/m.test("12\r\n"));
console.log(/caf\b/.test("café"));
console.log(/\bé/u.test("é"));
console.log("ab\ncd\n".match(/^\w+$/gm));
console.log(/\Aa/.test("a"), /a\z/.test("a"));

// Output on Node 22:
// false
// true
// true
// false
// [ 'ab', 'cd' ]
// false false

In practice

  • Python re — `re.match` anchors at the start implicitly and `re.fullmatch` at both ends (since 3.4), which is the call to use for validation because `$` accepts a trailing newline. Observed on 3.13.
  • GNU grep -P — PCRE2 10.42 with DOLLAR_ENDONLY set and no MULTILINE under `-z`; `printf 'a\nb' | grep -zcP '^b'` prints `0` because `^` only matches at the start of the NUL-separated record.
  • Go regexp — `$` without `(?m)` is the absolute end, so `MatchString("12\n")` is false for `^\d+$`; `\A` and `\z` exist, `\Z` does not. `(?m)^\d+$` finds `12` and `34` in `12\n34\n`. Observed on Go 1.24.
  • V8 Irregexp — The `m` flag treats `\r`, U+2028 and U+2029 as line terminators besides `\n`; there is no `\A` or `\z`. Observed on Node 22.22.

Trade-offs

Pros

  • Anchors make a pattern say exactly where it applies, which is what separates validation from search.
  • `\b` stops `cat` from matching inside `concatenate` for ASCII text without any lookaround.
  • `m` turns one pattern into a per-line scanner for logs and config files.

Cons

  • The trailing-newline behaviour of `$` (Python, PCRE2) lets values such as `"admin\n"` through a validator.
  • `\b` is wrong for non-ASCII words in Go, JavaScript and PCRE2 without extra options, and only Python gets it right by default.
  • `\A`, `\z`, `\Z` are available in different subsets of the engines, so only `^...$` without `m` is close to portable.

← All regex entries