Reverse regular expression in Java

蓝咒 提交于 2019-12-10 17:10:03

问题


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


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/10545250/reverse-regular-expression-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!