DEV Community

meng meng
meng meng

Posted on Originally published at meng4099244-ship-it.github.io

Regex Tester: Why My "Fully Anchored" Date Pattern Accepted a Trailing Newline (Python, Node, and the Browser)

Last month a customer pasted a renewal date into our billing portal, and the backend saved 2026-01-31\n — trailing newline included — straight into a Postgres date column. The nightly import job died at 2 a.m. with invalid input syntax for type date: "2026-01-31\n".

The strange part: my validator used ^\d{4}-\d{2}-\d{2}$, and CI was green. It took me an embarrassing hour to work out why a "fully anchored" pattern let that string through. Since then I debug regexes with a fixed routine: one probe script, one cross-runtime check, and a free online regex tester for the times I don't want to open an editor at all. Here's the routine.

Method 1: a probe script (Python 3.11)

The first move is to stop guessing and print what the pattern actually does. Nothing fancy, just the standard library:

# probe.py — Python 3.11.1, standard library only
import re

PATTERN = r"^\d{4}-\d{2}-\d{2}$"
samples = ["2026-01-31", "2026-01-31\n", "2026-1-31", "x2026-01-31"]

for s in samples:
    m = re.match(PATTERN, s)
    f = re.fullmatch(PATTERN, s)
    print(f"{s!r:18} match: {bool(m)!s:5} fullmatch: {bool(f)}")
Enter fullscreen mode Exit fullscreen mode

Output on my machine:

'2026-01-31'       match: True  fullmatch: True
'2026-01-31\n'     match: True  fullmatch: False
'2026-1-31'        match: False fullmatch: False
'x2026-01-31'      match: False fullmatch: False
Enter fullscreen mode Exit fullscreen mode

There it is. re.match with $ happily accepts the trailing newline, because $ also matches just before a final newline — a Perl inheritance documented in the Python re module docs. re.fullmatch is the honest one. Fifteen lines of probing beat an hour of staring at the pattern.

Method 2: the same pattern in Node (22.x)

Our portal's client-side validation is JavaScript, so the "same" pattern lives there too. I ported the probe:

// probe.mjs — Node 22.13.1
const PATTERN = /^\d{4}-\d{2}-\d{2}$/;
const samples = ["2026-01-31", "2026-01-31\n", "2026-1-31", "x2026-01-31"];

for (const s of samples) {
  console.log(JSON.stringify(s).padEnd(18), "test:", PATTERN.test(s));
}
Enter fullscreen mode Exit fullscreen mode
'2026-01-31'       test: true
'2026-01-31\n'     test: false
'2026-1-31'        test: false
'x2026-01-31'      test: false
Enter fullscreen mode Exit fullscreen mode

A different answer for the newline case. In JavaScript, $ without the m flag matches only at the very end of the string — the semantics are spelled out on the MDN RegExp page. So my Python server accepted 2026-01-31\n while my JS client would have rejected it. The only reason the bad value got through was that the client-side check had been commented out during a refactor.

Two "equivalent" regexes, two answers. I now treat every ported pattern as guilty until probed in both runtimes.

Method 3: when I just want an answer — the browser

Sometimes the fix is obvious and I only need to confirm one thing: does this pattern match this string, with these flags? Opening an editor for that is overkill. Pasting the pattern and the suspect input into this browser-based tool answers it in seconds. You see the match highlighted in the sample text and its exact position, and flipping a flag like m or i takes one click instead of a re-run.

It also handles the awkward cases where pasting matters. Customer data never leaves my machine because everything runs client-side, which turned out to matter more than I expected once I started doing this at work with real order IDs. And when I'm weighing two candidate fixes side by side, I keep both patterns in adjacent tabs of the regex testing tool and eyeball the highlighting — terminal output has never made that comparison as obvious for me.

Three traps that keep catching people

1. $ is not "end of string" in Python. As shown above, re.match(r"^\d{4}$", "2026\n") returns a match. Use re.fullmatch instead, or anchor with \Z if you must — though Python 3.14 deprecates \Z, so fullmatch is the future-proof choice. JavaScript has no such surprise without the m flag, which is exactly why the two runtimes disagree.

2. Escapes copied from config files. My validation patterns live in a JSON config, and one wrong level of escaping blows up Python at import time:

Traceback (most recent call last):
  File "validate.py", line 12, in <module>
    PATTERN = re.compile(cfg["pattern"])
re.error: bad escape \m at position 5
Enter fullscreen mode Exit fullscreen mode

Node is quieter about the same mistake: new RegExp("\\m") does not throw — it silently treats \m as a literal m. Only the u flag turns it into SyntaxError: Invalid regular expression: /\m/u: Invalid escape. So the JS port "worked" while matching something completely different. Rule of thumb: compile config-driven patterns at startup, never at request time.

3. Catastrophic backtracking. A colleague once merged two rules into ^(\d+)+$ — nested quantifiers, the classic ReDoS shape. Against a 31-character non-match like "1111111111111111111111111111111x", Python 3.11 spun for over 90 seconds before I killed the process; Node froze the same way. The re module gained atomic groups and possessive quantifiers in 3.11, so ^\d++$ or (?>\d+)+$ collapses the pathological path. If a validation endpoint hits 100% CPU with no traffic spike, look at the newest regex first.

What I reach for when

Situation Tool
Production accepted garbage, need the exact match Python probe: fullmatch + repr output
Pattern exists in two runtimes, results differ Node probe, compare line by line
Quick "does this match?" while writing the pattern Browser regex tester
CPU spike with no matching traffic Hunt for nested quantifiers first

The probe script lives in my snippets folder and earns its keep weekly. The browser tool covers everything in between — no install, no editor, no excuse for shipping an untested pattern again.

More free browser-based utilities at utilvy.com.

Top comments (1)

Collapse
 
mp3sss31 profile image
mp3sss •

The trailing-newline trap is such a good reminder that $ is not an absolute end anchor in these runtimes; it matches just before a final newline, so a half-anchored match passes input that a real full-string check rejects. The reliable fix is either a true full-match primitive, such as re.fullmatch or an explicit end check in JavaScript, or an absolute end anchor where the engine offers it, with trimming kept as a defense-in-depth layer rather than the validator itself. Worth probing the same sample in the browser runtime too, since client-side and server-side regex semantics can differ even when the pattern looks identical.