Regex replace string not in quotation marks (one or two)

I have an input line

it is either "this or that" or "this or that"

which should be translated into

this || "it or" || "one or the other"

So, the attempt consists in searching for the appearance of the string (or) inside the string and replacing it with another string (||). I tried the following code

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

Output signal

this || "it or" || 'this is || what

The problem was that the string inside the single quote was also replaced. As for the code, the style is just for example. I would compile the template and reuse it when I get this to work.

+4
source share
1 answer

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

All Articles