繁体   English   中英

正则表达式替换不在引号内的字符串(单引号或双引号)

[英]Regex to replace a string not within quotes (single or double)

我有一个输入字符串

这个或“那个或”或“这个或那个”

那应该被翻译成

这个|| “那或”|| “这个或那个”

因此,尝试在字符串中查找字符串(或)的出现,并将其替换为另一个字符串(||)。 我试过以下代码

Pattern.compile("( or )(?:('.*?'|\".*?\"|\\S+)\\1.)*?").matcher("this or \"that or\" or 'this or that'").replaceAll(" || ")

输出是

这个|| “那或”|| '这|| 那'

问题是单引号中的字符串也被替换了。 至于代码,样式只是一个例子。 我会编译模式并在我开始工作时重用它。

试试这个正则表达式: -

"or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)"

它匹配or后跟任何字符后跟一定数量的"' ,后跟任意字符直到结尾。

String str = "this or \"that or\" or 'this or that'";
str = str.replaceAll("or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)", "||");        
System.out.println(str);

输出: -

this || "that or" || 'this or that'

如果您与"'不匹配,上述正则表达式也将替换or

例如: -

"this or \"that or\" or \"this or that'"

它也将替换or替换上述字符串。 如果您希望在上述情况下不替换,可以将正则表达式更改为: -

str = str.replaceAll("or(?=(?:[^\"']*(\"|\')[^\"']*\\1)*[^\"']*$)", "||");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM