Check whether two regular expressions are equivalent
How to check if two regular expressions are equivalent: what equivalence means, how automata-based checks work, where they fail, and how to test and share patterns safely.
Two regular expressions are equivalent when they accept exactly the same set of strings. That sounds like a comparison of two lines of text, but the pattern text tells you very little. Patterns that look different can match identically, and identical patterns can behave differently under another engine or flag. This review explains what an equivalence check establishes, which method suits which situation, and what can still go wrong after a verified pattern is copied into real code.
Short answer: when an equivalence check is worth relying on
A formal equivalence check is worth using when you refactor, simplify or merge patterns built from classic regular features: literals, character classes, alternation, grouping and repetition. Its main benefit is that it covers every possible input, not just the ones you thought to test. The tradeoff is that the result only holds for the features the checker models, under its assumptions about flags, alphabet and match mode. Outside that scope you are back to testing, which can reveal differences but cannot prove there are none.
In some cases it is better to skip the rewrite or skip the regex. If the pattern uses backreferences, if your code depends on which alternative or capture group is returned, or if the rewrite is only cosmetic, keep the original and add a plain-language comment. If the task is only to find or compare a fixed string, an ordinary string comparison is simpler, faster and has nothing to prove.
What "equivalent" means, and what it does not
Comparing two regular expressions can mean three different things. Textual equality asks whether the characters are identical. Language equivalence asks whether both patterns accept the same set of whole strings. Behavioral equivalence asks whether both produce the same matches, positions and captures, at acceptable speed, in a particular engine. Most online tools and libraries that claim to check equivalence answer the second question. Production code usually depends on the third.
Different text, same language (strings of a and b, including the empty string):
(a|b)*
(a*b*)*
Same language, different match when searching "ab" in a backtracking engine:
a|ab -> finds "a"
ab|a -> finds "ab"
Identical text, different language depending on engine:
\d -> ASCII digits only in JavaScript;
Unicode decimal digits in Python 3 str patterns and .NET by default
How a formal check works
For patterns limited to classic regular features, equivalence is decidable. The standard method converts each pattern into a finite automaton, makes it deterministic, minimizes it, and compares the results. For a given language and alphabet, the minimal deterministic automaton is unique apart from the names of its states, so two patterns are equivalent exactly when their minimal automata match. Another method builds an automaton for the strings accepted by one pattern but not the other and checks whether it accepts anything. If it does, any accepted string is a concrete counterexample, which is usually more useful than a bare yes or no.
This is not always cheap. Equivalence of regular expressions is PSPACE-complete in general, and making an automaton deterministic can increase its size exponentially. A standard example is (a|b)*a(a|b){n}, whose smallest deterministic automaton grows exponentially as n increases. Most everyday patterns are small enough to check quickly. Large counted repetitions and large Unicode character classes are the usual reasons a checker slows down or gives up.
The checker must also use the same alphabet as your engine. Dot, negated classes such as [^x], and shorthand classes all depend on which characters exist. A checker that assumes ASCII can report two patterns as equivalent even though they differ on accented letters, non-Latin digits or line separators.
Features that break or weaken the check
- Backreferences such as (a+)\1 describe languages that are not regular, and equivalence for patterns with backreferences is undecidable in general. Expect a checker to reject them or handle only special cases.
- Lookahead and lookbehind of bounded form can be expressed with automata in theory, but many checkers do not support them. Confirm that the tool reports an error rather than silently ignoring the construct.
- Possessive quantifiers and atomic groups can change what is accepted: a*+a never matches, while a*a matches one or more a's.
- Lazy and greedy quantifiers, such as a+? and a+, accept the same strings but can return different matches when searching.
- Anchors depend on mode: with the multiline flag, ^ and $ match at line boundaries, and in Python $ also matches just before a trailing newline at the end of the input.
- Case-insensitive matching, Unicode mode, and the meaning of \w, \d, \b and dot all vary by engine and flag, so a check is valid only for the configuration it assumed.
Same language, different behavior
Most code searches for a match inside a string rather than testing whether the whole string matches. Backtracking engines, including those in JavaScript, Python, Java, PCRE and .NET, try alternatives in order and return the first that succeeds. That is why a|ab and ab|a return different matches for the same input. POSIX engines that use leftmost-longest rules would return "ab" for both. Capture group numbering and contents can also change in a rewrite that preserves the language, which breaks any code reading groups by index.
Performance is not covered either. The patterns (a+)+b and a+b accept the same strings, but on a backtracking engine the nested quantifier can take exponential time on a long run of a's with no b. An equivalence checker will call the two interchangeable, yet only one is safe to run on untrusted input. When a rewrite is meant to remove this kind of backtracking risk, the equivalence check confirms the meaning is unchanged. Whether the risk is actually gone has to be tested separately.
// JavaScript: same language, different search results
"ab".match(/a|ab/)[0]; // "a"
"ab".match(/ab|a/)[0]; // "ab"
Testing when a proof is not available
When the patterns use features a checker cannot handle, or you need to confirm behavior in your actual engine, run both patterns on the same inputs and compare the results. Small inputs can be enumerated exhaustively. Build an alphabet from the characters that appear in the patterns, then add one character that appears in neither, a newline, and a non-ASCII letter or digit. Enumerate every string up to a chosen length. Add randomly generated longer inputs, the empty string, a trailing newline, and lengths on either side of any counted repetition.
import itertools
import re
def first_difference(p1, p2, alphabet, max_len, flags=0):
r1 = re.compile(p1, flags)
r2 = re.compile(p2, flags)
for n in range(max_len + 1):
for chars in itertools.product(alphabet, repeat=n):
s = "".join(chars)
if bool(r1.fullmatch(s)) != bool(r2.fullmatch(s)):
return s
return None
# Checks every string up to length 8 over the given alphabet
print(first_difference(r"(a|b)*", r"(a*b*)*", "abx\n", 8))
print(first_difference(r"\d+", r"[0-9]+", "1a\u0663", 3))
Read the result narrowly. A clean run means no difference exists among the strings tried, in that engine, under those flags. A difference that only appears at length 11 will not show up with a limit of 8. The script above compares full matches. If your code searches, change the comparison to look at match positions with search or finditer, and compare captured groups too if your code uses them. In Python 3 the second call should report the Arabic-Indic digit three (U+0663), since \d matches it and [0-9] does not.
Choosing an approach
| Approach | Can prove equivalence | Finds counterexamples | Handles backreferences | Main caveat |
| Comparing pattern text | No | No | Not applicable | Says nothing about meaning |
| Automata-based checker | Yes, within supported features | Yes, if it returns a witness string | No, in general | Valid only for its dialect, flags, alphabet and match mode |
| Bounded exhaustive testing | No, only up to the length limit | Yes | Yes, using the real engine | Grows quickly with alphabet size and length |
| Random or property-based testing | No | Yes | Yes, using the real engine | Can miss rare edge cases |
| Review of match, capture and performance behavior | No | Sometimes | Yes | Needed even after language equivalence is proven |
Using an online checker
No evidence was collected on any specific online regex equivalence service, so this review does not rate or recommend one. When evaluating a tool, check these points: which regex dialect it parses and which flags it applies; whether it rejects unsupported constructs rather than silently dropping them; whether it compares full matches or search behavior; what alphabet it assumes; and whether it returns a counterexample string when the patterns differ. A tool that answers only yes or no gives you nothing to verify.
Patterns can reveal more than they appear to, such as internal hostnames, account formats or the structure of keys and tokens. Do not assume a web tool discards what you enter, or processes it only in your browser, based on how it looks or how it is described in marketing copy. Check its stated data practices. For sensitive patterns, use a local library or a script like the one above.
Will the result survive copying and sharing?
A pattern checked in one place is often pasted into another, where an extra layer of escaping applies. In ordinary string literals in Java, C#, C and similar languages, every backslash in the pattern must be doubled. Python raw strings and C# verbatim strings avoid this. JavaScript regex literals need no doubling, but patterns passed to the RegExp constructor as strings do. Mistakes here can change the meaning without raising an error: in a non-raw Python string, \b is a backspace character, not a word boundary.
Flags usually travel separately from the pattern. Copying the body of a JavaScript literal such as /^\d+$/m drops the multiline flag, and options passed as function arguments in Python, Java or .NET are easy to leave behind. Repeat any equivalence check with the flags as actually deployed.
Rich-text editors, chat apps and document tools can replace straight quotes with curly ones, turn a hyphen-minus into an en dash, or insert non-breaking and zero-width spaces. In a regex each of these is a literal character, so the pattern accepts different strings while looking the same. Share patterns in code blocks or plain-text files. If a pasted pattern behaves unexpectedly, inspect its code points instead of trusting what is displayed.
An equivalent rewrite can also make a pattern harder to read. A shorter pattern is not necessarily easier to review, and text search will not find an old form of a pattern under its new spelling. How screen readers announce punctuation-heavy strings depends on the product and its verbosity settings. No scoped test was available for this review, so do not assume a pattern is understandable when read aloud. A plain-language description of what the pattern accepts, with a few strings that match and a few that do not, serves both human reviewers and assistive technology. Verbose mode, such as Python's re.VERBOSE or the x flag in Perl and PCRE, lets you add whitespace and comments where the engine supports it. Not every engine does.
Gaps in this review
No specific equivalence tools or online services were tested. No timings or size limits were measured. No assistive technology was evaluated. Statements about engine behavior reflect the documented semantics of the named engines and should be confirmed against the versions and flags you actually use.