Try this regex: -
"or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)"
It matches or , followed by any characters, followed by a certain number of " or ' pairs, followed by any characters to the end.
String str = "this or \"that or\" or 'this or that'"; str = str.replaceAll("or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)", "||"); System.out.println(str);
Result: -
this || "that or" || 'this or that'
The above regex will also replace or if you have a mismatch of " and ' .
For example, for example:
"this or \"that or\" or \"this or that'"
It will also replace or with the lines above. If you want it not to be replaced in the above case, you can change the regex to: -
str = str.replaceAll("or(?=(?:[^\"']*(\"|\')[^\"']*\\1)*[^\"']*$)", "||");
source share