开发者

How to undo replace performed by regex?

In java, I have the following regex ([\\(\\)\\/\\=\\:\\|,\\,\\\\]) which is compiled and then used to escape each of the special characters ()/=:|,\ with a backslash as follows escaper.matcher(value).replaceAll("\\\\$1")

So the string "A/C:D/C" would end up as "A\/C\:D\/C"

Later on in the process, I need to undo that replace. That means I need to match on the combination of \(, \), \/ etc. and replace it with the character immediately following the backslash character. A backslash followed by any other character should not be matched and there could be cases where a special character will exist without the preceeding backslash, in which case it shouldn't match either.

Since I know all of the cases I could do something like

myString.replaceAll("\\(", "(").replaceAll("\\)", ")").replaceAll("\\/", "/")...

but I wo开发者_StackOverflow社区nder if there is a simpler regex that would allow me to perform the replace for all the special characters in a single step.


That seems pretty straightforward. If this were your original code (excess escapes removed):

Pattern escaper = Pattern.compile("([()/=:|,\\\\])");

String escaped = escaper.matcher(original).replaceAll("\\\\$1");

...the opposite would be:

Pattern unescaper = Pattern.compile("\\\\([()/=:|,\\\\])");

String unescaped = unescaper.matcher(escaped).replaceAll("$1");

If you weren't escaping and unescaping backslashes themselves (as you're doing), you would have problems, but this should work fine.


I don't know java regex flavor but this work with PCRE

replace \\ followed by ([()/=:|,\\]) by $1

in perl you can do

$str =~ s#\\([()/=:|,\\])#$1#g;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜