英文:
regex to match double qoutes not followed by odd number of backslash
问题
我想将不跟随奇数个反斜杠的双引号替换为空字符串。
例如:
字符串:"hello \" world \\","hello \\\" world\\\\"
正则表达式:?
结果:hello \" world \\,hello \\\" world\\\\
(在替换为空字符串后)
与此同时,\\ 和 \" 被替换为 \ 和 ",
我可以通过正则表达式\\ 和 \" 来做到这一点。
我需要一个正则表达式来替换不跟随奇数个\ 的 "。我正在制作一个简单的解析器,忽略 " " 内部的字符串,所以,有人能帮帮我。
英文:
I want to replace double-quotes not followed by odd number of backslash with empty string.
For eg:
String : "hello \" world \\" , "hello \\\" world\\\\" 
Regex : ?
Result : hello \" world \\  , hello \\\" world\\\\
(after replaced with empty string )
at the same time the \\ and \" are replaced by \ and "
i do that simply with regex\\ and \"
I need the regex to replace " not followed by odd number of \ . I am making a simple parser that ignores the string inside " "
so, somebody help.
答案1
得分: 1
这个正则表达式将给你精确的结果
应该使用 + 而不是 {0,20},但是Java不允许这样做,
所以你可以使用预期的最大数量的 \ 的两倍,而不是20
    String text = "\"hello \\\" world \\\\\\\" , \\\"hello \\\\\\\\\\\" world\\\\\\\\\\\\\\\"";
    String newText = text.replaceAll("(?<!((?<!\\\\)(\\\\)(\\\\\\\\){0,20}))\"", "");
    System.out.println("newText = " + newText);
英文:
this regex will give you the exact result
it should be + instead of {0,20} but java won't allow that,
So you can put double the maximum expected number of expected \ instead of 20
    String text = "\"hello \\\" world \\\\\" , \"hello \\\\\\\" world\\\\\\\\\"";
    String newText = text.replaceAll("(?<!(?<!\\\\)(\\\\)(\\\\\\\\){0,20})\"", "");
    System.out.println("newText = " + newText);
专注分享java语言的经验与见解,让所有开发者获益!



评论