How to reverse regular expression in Java? For example, 'ab.+de' => 'ed.+ba'.
3 Answers
It would actually be much easier to reverse the haystack than the needle. And since Matcher
takes a CharSequence
instead of a String
, you can do so with trivial overhead by simply wrapping the String
(see the answers to Reverse a string in Java, in O(1)?).
With this knowledge, you can create an alternate version of Matcher
that can appear to be reversing the pattern, but is really just reversing the input.

- 1
- 1

- 80,126
- 17
- 159
- 190
wow.
You need to build a parser for regular expression and reverse all of the tokens/parts.
in this case
ab.+de is
a , b, .+ , d , e
and reverse this is
e, d, .+, b, a
now imagine groups
((ab)(.+de))
the reverse is
((ed.+)(ba))

- 4,387
- 2
- 22
- 35
-
1+1 Seems like a recursive function could be a good solution: Keep recursively reversing subgroups and then concatenating subgroups together (in reverse) on the way back up the stack. – Paul May 11 '12 at 04:22
-
special regular expressions like (?<= expression) needs a special attention because it is a look behind. But in java... well... probably it is not work – Tiago Peczenyj May 11 '12 at 04:55
-
Yeah, I would implement this just for real regular expressions for regular languages. Which is basically just concatenation (`.abc`), alternation `.|a|b|c`, and finite counting (`.{2}a+b?c{,3}`). – Paul May 11 '12 at 05:34
-
Nope, those aren't part of a real regular language either. Unless you can implement it just with the three rules concatenation, alternating, and finite counting (grouping can also be used in combination with any of those), it's not a real regular expression because it defines something more expressive than a regular language. – Paul May 11 '12 at 05:42
-
If anyone is interested in a Java solution, I implemented a library to do just that. https://github.com/vsch/reverse-regex. Handles all valid Java regex constructs and provides utility classes to wrap pattern and matcher for reverse searches to handle all need mappings and reversals. – vladsch Jan 14 '17 at 19:32
Tiago Peczenyj is correct and both back references, capturing groups and named groups need to be handled. Named groups because there is no limitation in Java RegEx that a named group needs to be back referenced by name, it can be back referenced by number like any other capturing group.
If anyone is interested in a Java solution, I implemented a library to do just that. https://github.com/vsch/reverse-regex.
Handles all valid Java regex constructs and provides utility classes to wrap pattern, matcher and input for reverse searches to handle all need mappings and reversals.