正则表达式用于匹配未跟随奇数反斜杠的双引号。

huangapple go评论54阅读模式
英文:

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 = &quot;\&quot;hello \\\&quot; world \\\\\&quot; , \&quot;hello \\\\\\\&quot; world\\\\\\\\\&quot;&quot;;
    String newText = text.replaceAll(&quot;(?&lt;!(?&lt;!\\\\)(\\\\)(\\\\\\\\){0,20})\&quot;&quot;, &quot;&quot;);
    System.out.println(&quot;newText = &quot; + newText);

huangapple
  • 本文由 发表于 2020年8月15日 01:10:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63417203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定