The Challenge
Given a valid regex, output a regex that that matches the same set of strings, but reversed.
The Task
This challenge uses the most basic regex operations: ^
, $
, ?
, +
, *
, []
, {}
, |
. There's no such thing as capture groups or any of that complicated stuff. Special characters can be escaped.
Sample Input/Output
Note: Invalid input will never be given, and there are generally multiple possible answers for a given input!
Input | Sample Output
-----------|-------------
abc | cba
tuv? | v?ut
a(b|c) | (c|b)a
1[23] | [23]1
a([bc]|cd) | (dc|[bc])a
^a[^bc]d$ | ^d[^bc]a$
x[yz]{1,2} | [yz]{1,2}x
p{2} | p{2}
q{7,} | q{7,}
\[c[de] | [de]c\[
ab[c | <output undefined>
a(?bc) | <output undefined>
a[]]bc | <output undefined>
Demo
Working demo that demonstrates correct inputs/outputs. This has some additional logic for validating inputs that isn't necessary in a real answer. Consider invalid inputs to be undefined behavior.
Specifics
For simplicity, all special characters either have their special meaning or are escaped; that is, [[]
isn't a character range for [
. Length ranges come from standard POSIX EREs; that is, {n}
, {n,}
, and {n,m}
are supported. The character ranges []
and [^]
are supported. Because of these rules, and since no invalid input is given, you really need only copy the contents of these directly to the output. Lastly, greediness doesn't matter, i.e. it doesn't matter if the reversed regex finds a different match first, it just needs to find a match for the same set of strings.
Scoring
Smallest program in bytes (barring cheating such as network requests) wins. Program can either use real IO or simply define a function.
?
to attach to. Try typing/a(?bc)/
into the browser's console. \$\endgroup\$(^a|b)(c$|d)
as a test case though. \$\endgroup\$(a)?(b)+
↦(b)+(a)?
? \$\endgroup\$()
, which is used in your example. \$\endgroup\$