正则表达式替换不在引号内的字符串(单引号或双引号)
我有一个输入字符串
这个或“那个或”或“这个或那个”
那应该被翻译成
这个|| “那或”|| “这个或那个”
因此,尝试在字符串中查找字符串(或)的出现,并将其替换为另一个字符串(||)。 我试过以下代码
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)*[^\"']*$)", "||");