Skip to content

Lesson 7 of 13 · 22m

Flags, Lines, and Unicode: Where Correct Patterns Go Wrong

Multiline and dotall semantics, the trailing-newline validation bypass, CRLF, code units versus code points, and the stateful g flag.

A pattern that passes every unit test can still break the first week in production. The input arrives as a Windows-exported CSV, a username contains an emoji, a "digits only" field accepts Arabic-Indic numerals. None of these are exotic. They're Tuesday. This is the checklist to run before trusting a regex with real-world text.

Flags that change meaning

  • i: case-insensitive (re.I)
  • m: ^/$ match at line breaks, not just input edges (re.M)
  • s: . matches newlines ("dotall", re.S)
  • x: verbose — insignificant whitespace and # comments (re.X; not in JS)
  • u / v (JS): Unicode code-point mode and \p{...} property escapes; v (ES2024) adds set notation like [\p{ASCII}&&\p{L}]
  • g / y (JS): global and sticky — both make the regex object stateful
  • re.A (Python): restrict \w, \d, \s to ASCII

$ and the newline you forgot

In JavaScript without m, $ means end of input. In Python, PCRE, and Java, $ also matches just before a trailing newline:

import re
re.match(r"^[a-z0-9]+$", "admin\n")     # matches — the newline slips through validation
re.fullmatch(r"[a-z0-9]+", "admin\n")   # None
re.match(r"^[a-z0-9]+\Z", "admin\n")    # None — \Z is Python's absolute end (\z in PCRE/Java/Ruby)

Ruby goes further: ^ and $ are always line anchors, so /^https?:\/\// happily validates "javascript:alert(1)\nhttp://x". Rails refuses ^/$ in validates :format for exactly this reason — it raises ArgumentError at boot. Use \A and \z.

CRLF: the invisible \r

const csv = "id,name\r\n1,alice\r\n2,bob\r\n";
console.log(csv.split("\n").map(l => /^\d+,\w+$/.test(l)));    // [false, false, false, false]
console.log(csv.split(/\r?\n/).map(l => /^\d+,\w+$/.test(l))); // [false, true, true, false]

Everything Excel exports and Windows services write ends in \r\n. Split on \n alone and each line keeps a trailing \r that breaks every $. It's invisible in most terminals; cat -A shows it as ^M.

Code units versus code points

console.log(/^.$/.test("😀"));                    // false — UTF-16 sees two code units (a surrogate pair)
console.log(/^.$/u.test("😀"));                   // true
console.log("café".match(/\w+/)[0]);               // "caf" — \w is ASCII-only in JS
console.log("café".match(/\p{L}+/u)[0]);           // "café"
console.log("café".match(/\p{L}+/u)[0]);      // "cafe" — the combining accent is \p{M}, not \p{L}

Normalize first — s.normalize("NFC") merges the combining mark into é — then match. Skipping that step is how café typed on a Mac (decomposed e + U+0301) fails a lookup keyed on the precomposed form. Python runs the other way: \d and \w are Unicode-aware on str, so re.fullmatch(r"\d+", "١٢٣") succeeds. Fine for prose, wrong for account numbers. Write [0-9] or set re.ASCII for identifiers.

The g flag makes a regex stateful

const re = /error/g;
console.log(re.test("error: disk full"));   // true  — lastIndex is now 5
console.log(re.test("error: oom killed"));  // false — the search resumed at index 5

A module-level /.../g passed to test() alternates true and false across calls. This bug survives code review because each call looks correct. Drop g for boolean checks; keep it for matchAll and replace-everything. The same statefulness makes exec() loop until null — the correct way to iterate is while ((m = re.exec(s)) !== null), which advances lastIndex each pass; a zero-width match (like (?=aba)) needs a manual re.lastIndex++ or it loops forever.

Field notes

  • In Python, validate with re.fullmatch. Never ^...$.
  • [\s\S] was the pre-s-flag idiom for "any character including newline." Old code still has it.
  • LC_ALL=C makes grep and sed operate on bytes: faster, but . no longer matches a multi-byte character as one unit.
  • Case-insensitive matching folds case simply; Turkish dotless ı/İ and German ß won't behave how your users expect.
  • \p{N} covers all Unicode numbers — including Roman numerals and superscript digits. When you mean ASCII digits, write [0-9].

Keep reading

Related articles from the SudoSecurity blog.