试试这个正则表达式: –
"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'
如果您与“和”不匹配,上述正则表达式也将替换或.
例如: –
"this or \"that or\" or \"this or that'"
它也将取代或替换上述字符串.如果您希望在上述情况下不替换它,可以将正则表达式更改为: –
str = str.replaceAll("or(?=(?:[^\"']*(\"|\')[^\"']*\\1)*[^\"']*$)", "||");