Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse regular expression in Java

How to reverse regular expression in Java? For example, 'ab.+de' => 'ed.+ba'.

like image 496
mgukov Avatar asked Feb 21 '23 13:02

mgukov


2 Answers

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))

like image 195
Tiago Peczenyj Avatar answered Feb 27 '23 17:02

Tiago Peczenyj


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.

like image 36
Mark Peters Avatar answered Feb 27 '23 15:02

Mark Peters