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



我有一个输入字符串

这个或"

那个"或"这个或那个"

应该翻译成

这 ||"那个或" ||"这个或那个"

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

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)*[^"']*$)", "||");

最新更新