Skip to main content

A pattern works here but fails in my application

Start with the engine, operation, flags, and actual input. Each can differ even when the visible pattern looks identical.

Verify the engine and operation​

  1. Select the flavor corresponding to your application's regex library.
  2. Record the target runtime version.
  3. Compare matching with matching, or replacement with replacement.
  4. Verify whether the application searches anywhere or requires the entire input.

A framework can also wrap its language's regex library with additional constraints.

Remove one layer of escaping​

In JavaScript, these two expressions use the same regex:

;/\bORD-[0-9]{4}\b/g
new RegExp('\\bORD-[0-9]{4}\\b', 'g')

The string form needs doubled backslashes. Otherwise, \b in a JavaScript string becomes a backspace character. The regex101 pattern field expects \bORD-[0-9]{4}\b, without the surrounding string quotes.

JSON, shell commands, SQL strings, and log-processing configuration can introduce additional escaping layers. Verify the exact pattern that reaches the regex library after those layers are decoded.

Compare the flags​

SymptomFirst comparison
Only the first result appearsGlobal matching or the host's iteration method
Uppercase matches but lowercase failsCase sensitivity
A pattern works on one line but not severalm, s, and line endings
. does not match a newlineDot-all mode, such as JavaScript s
Anchors match an unexpected lineMultiline mode, such as JavaScript m
A backreference or lookbehind produces an errorEngine support and runtime version

The g flag is an editor operation control for some flavors, rather than a flag accepted by that language's library. The code generator shows the target language's iteration syntax.

Inspect the actual characters​

A visible \n can mean two characters or one newline. A copied space can be a nonbreaking space. Different files can use LF or CRLF line endings. Unicode text can contain visually identical sequences with different code points.

In JavaScript, JSON.stringify(input) reveals escapes for line breaks and some other characters. When you prepare a report, include the escaped synthetic input alongside its readable form.

PCRE-based applications can also differ in byte width and Unicode configuration. Do not treat the editor's character positions as byte offsets in an unrelated host application.

Reproduce the order example​

const input = 'ORD-0042 pending\nORD-0187 sent'
const pattern = /\bORD-(?<id>[0-9]{4})\b/g
console.log([...input.matchAll(pattern)].map((match) => match.groups.id))
// ['0042', '0187']
  1. Run this example in your JavaScript runtime.
  2. Run the same pattern and input in the JavaScript flavor.
  3. Change one element at a time until the difference returns.

For replacement problems, compare the replacement expression as well as the pattern. For exact whole-input validation, account for line-ending and multiline boundaries.