Regex exactly once
How to make a regex match something exactly once: why {1} isn't enough, patterns with and without lookahead, Unicode pitfalls, engine limits, and when plain code is better.
"Exactly once" in a regular expression can mean several different things. The quantifier most people try first, {1}, doesn't enforce any of them by itself. This review explains what each pattern actually checks and where it breaks. It also covers when counting in ordinary code is the better choice.
Short answer: is a regex the right tool?
A regex is a good fit when you need the check as a single pattern. Typical cases are form validators, configuration fields, linter rules, and search tools that accept a regex and nothing else. The main benefit is one self-contained rule you can paste into whatever accepts a pattern.
The main tradeoff is that "exactly one occurrence of a substring" requires lookahead or a tempered token. Some engines don't support these constructs, and they are harder for humans to read and review. If you can write even one line of code, counting matches and comparing the count to 1 is usually clearer and easier to verify.
What "exactly once" can mean
- The whole input is exactly one item, such as a single character or token. Anchors handle this: ^a$.
- A fixed run of repetitions in one place, such as exactly three digits: ^\d{3}$. This is "exactly n" rather than "exactly once".
- The input contains exactly one occurrence of something somewhere, with none elsewhere. This is the case that needs extra construction.
- A replacement should happen only once, to the first match, and leave later matches alone. This is a setting on the replace call, not part of the pattern.
Why {1} does not enforce it
The pattern a{1} means exactly the same thing as a. A quantifier controls how many times a token repeats at one position in the match. It doesn't count occurrences across the whole string. Searching "banana" for a{1} succeeds at the first "a", and nothing in the pattern objects to the other two. To limit the total count, the pattern must cover the entire input with anchors and explicitly rule out a second occurrence.
Patterns by goal
| Goal | Pattern | Needs lookaround? |
| Whole input is a single "a" | ^a$ | No |
| Input contains exactly one comma | ^[^,],[^,]$ | No |
| Input contains exactly one "foo" | ^(?!.foo.foo).foo.$ | Yes |
| Same goal, tempered-token form | ^(?:(?!foo).)foo(?:(?!foo).)$ | Yes |
| Exactly one whole word "cat" | ^(?!.\bcat\b.\bcat\b).\bcat\b.$ | Yes |
| Replace only the first match | JavaScript replace without the g flag; Python re.sub with count=1 | No |
Single characters are the easy case. The comma pattern allows any number of non-commas, one comma, and then any number of non-commas up to the end. A second comma has nowhere to fit, so the match fails. The pattern uses no lookaround, so it works in practically every engine, including POSIX grep and sed.
Multi-character substrings can't be excluded with a character class, so they need an assertion. The negative-lookahead form says "from the start, two occurrences can't be found" and then requires one. The tempered-token form consumes one character at a time, but only where "foo" doesn't begin, on both sides of the single allowed "foo". The two forms accept the same inputs. Choose whichever your team finds easier to read.
// JavaScript: exactly one whole word "cat", across line breaks
const once = /^(?!.*\bcat\b.*\bcat\b).*\bcat\b.*$/s;
once.test("one cat here"); // true
once.test("cat and cat"); // false
once.test("concatenate"); // false: no word boundaries around "cat"
# Python: same check; fullmatch makes the outer anchors implicit
import re
pattern = r"(?!.*\bcat\b.*\bcat\b).*\bcat\b.*"
ok = re.fullmatch(pattern, text, flags=re.DOTALL) is not None
By default, the dot doesn't match a newline. Without the s flag in JavaScript or re.DOTALL in Python, a second occurrence on a later line goes unnoticed, and an input whose only occurrence sits on another line fails. You can enable that flag, or replace the dot with [\s\S]. If you want "exactly once per line" instead, use multiline mode, where ^ and $ match at line boundaries, and apply the pattern line by line.
What the pattern actually changes
A match or test doesn't change your text. It returns true or false, or the position of the match. Text changes only in a replace operation, and there "once" depends on the call, not the pattern. In JavaScript, String.prototype.replace with a regex that lacks the g flag replaces only the first match. In Python, re.sub(pattern, repl, text, count=1) does the same. Pass count as a keyword argument, because newer Python versions deprecate passing it positionally. If you need "replace only when there is exactly one match", run the exactly-once test first, then replace.
Overlapping occurrences
Decide whether overlaps count before you trust a pattern. Take "aaa" and the target "aa". Both substring patterns in the table accept it, because "aa" can't be found twice without sharing a character. If overlapping starts should count as separate occurrences, the check needs a zero-width lookahead at each start position.
^(?!(?:.*?(?=aa).){2})(?=.*aa)
This pattern rejects any input where "aa" begins at two different positions, so "aaa" fails and "aab" passes. In code, counting overlapping starts is simpler: len(re.findall(r"(?=aa)", text)) == 1 in Python.
"Exactly one character" and Unicode
The pattern ^.$ looks like "exactly one character". What counts as a character depends on the engine and its flags. In JavaScript without the u flag, the dot matches one UTF-16 code unit. An emoji outside the Basic Multilingual Plane takes two code units, so ^.$ fails on it. With the u flag, and in Python 3, the dot matches one code point.
Even one code point isn't always one visible character. Here are some cases where they differ:
• An "é" typed as "e" plus a combining acute accent is two code points.
• A flag emoji is two regional-indicator code points.
• Family and profession emoji are often several code points joined by zero-width joiners.
To match one user-perceived character, use \X, which matches an extended grapheme cluster. PCRE, Perl, and Python's third-party regex module support \X. Python's built-in re module does not. JavaScript has no \X, so Intl.Segmenter with grapheme granularity is the usual alternative. Unicode normalization to NFC merges some combining sequences into single code points, but not all of them, so don't rely on it for this purpose.
Will the pattern survive copying and sharing?
- Engine support: POSIX basic and extended regex, used by default grep and sed, has no lookaround. Neither does Go's regexp package or other RE2-based engines. GNU grep's -P option switches to PCRE where it is available. Check the documentation for the engine where the pattern will actually run.
- End anchors: in Python, $ also matches just before a trailing newline, so "cat\n" can pass an anchored check. Use \Z or re.fullmatch for a strict end. In JavaScript without the m flag, $ matches only at the true end of the input.
- Escaping layers: a pattern often passes through a string literal, JSON, or a shell before the engine sees it. In a non-raw Python string, \b is a backspace character, not a word boundary. In JSON, every backslash must be doubled.
- Pasted invisible characters: copying from rich-text editors, documents, or chat apps can bring along curly quotes, non-breaking spaces, or zero-width characters. These become literal parts of the pattern and silently prevent matches. If a pasted pattern fails for no visible reason, retype it or inspect its code points.
- Online testers: a tester set to a different flavor than your runtime can accept a pattern your code rejects, or the reverse. A successful test in one tool doesn't prove the pattern works everywhere.
Readability matters for anyone who maintains the pattern. Lookaround-heavy expressions are hard to review. A screen reader may read them symbol by symbol, or skip punctuation entirely, depending on its settings. Keep a plain-language sentence next to the pattern, such as "accepts input containing the word cat exactly once". Where the engine supports it, use verbose mode so the pattern can carry comments: re.VERBOSE in Python, or the x flag in PCRE and Perl. JavaScript has no standard verbose flag, so the plain-language description matters more there.
When plain code is the better choice
# Python
text.count("foo") == 1 # non-overlapping substring count
len(re.findall(r"\bcat\b", text)) == 1 # whole-word count
// JavaScript
text.split("foo").length === 2 // non-overlapping substring count
Use these whenever the surrounding system lets you run code. The intent is obvious at a glance, they need no lookaround support, and they are easy to change when the definition of an occurrence changes. Save the single-pattern versions for places that accept only a regex.
Evidence gaps
No test results, benchmarks, or tool-specific documentation were supplied for this review. The behavior described here comes from general regex semantics and widely documented engine features. It does not come from measured runs in a particular tester or library version. Performance is also unmeasured. Lookahead and tempered-token patterns rescan text and may be slow on very long inputs, but no figures are available here. Before relying on any of these patterns, test them in the exact engine, version, and flags your application uses, with inputs that include line breaks, overlaps, and multi-code-point characters.