Regular expressions and text guides

Why your regex misses: flags, anchors and escaping

Reproduce regex mismatches with positive and negative examples, then check multiline behavior, global matching and string escaping.

Nav Tools ·

Start with a small fixture

A pattern that matches a substring is not necessarily a validator for the whole value. For a simple ASCII account-name rule, anchors make the intended boundary explicit. Keep both passing and failing inputs beside the pattern.

The example allows 3–16 ASCII letters, digits or underscores. It is an illustrative rule, not a universal username policy.

Pattern: ^[A-Za-z0-9_]{3,16}$
Pass:    dev_42
Fail:    ab
Fail:    dev-42

Check the flags

i ignores case. g searches for multiple matches. m makes ^ and $ refer to line boundaries rather than only the beginning and end of the entire input. s lets the dot match line terminators.

Use m deliberately: a single valid line inside a multiline string can match an anchored pattern with m. If you want to validate one value, test the complete input and its line breaks.

Input:    cat
          CAT
Pattern:  cat
Flags g:  cat
Flags gi: cat, CAT

Count the escaping layers

A regex literal /\d+/ contains one backslash. In new RegExp("\\d+"), a JavaScript string consumes one escaping layer first. JSON strings add their own escaping rules.

In a tool’s pattern field, enter the pattern expected by that tool rather than copying quotes and slashes from source code. Nav Tools uses the JavaScript regex engine; PCRE, Go and Python can have different syntax or matching behavior.

Regex literal: /\d+/
JS constructor: new RegExp("\\d+")
Pattern field: \d+

Avoid a single happy-path test

Test an empty value, a near miss, line breaks, long input and Unicode where relevant. Change one part of the pattern at a time so the cause remains visible.

Nested ambiguous quantifiers can cause catastrophic backtracking. Prefer simpler patterns and explicit limits. The tester uses an isolated worker with a timeout; a passing interactive test does not establish production performance.

References

← Regular expressions and text guides