Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

java - Regex to replace a string not within quotes (single or double)

I have a input string

this or "that or" or 'this or that'

that should be translated to

this || "that or" || "this or that"

So the attempt is to look for an occurence of a string ( or ) within a string and replace it with another string ( || ). I have tried the following code

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

The output is

this || "that or" || 'this || that'

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this regex: -

"or(?=([^"']*["'][^"']*["'])*[^"']*$)"

It matches or which is followed by any characters followed by a certain number of pairs of " or ', followed by a any characters till the end.

String str = "this or "that or" or 'this or that'";
str = str.replaceAll("or(?=([^"']*["'][^"']*["'])*[^"']*$)", "||");        
System.out.println(str);

Output : -

this || "that or" || 'this or that'

The above regex will also replace or, if you have a mismatch of " and '.

For e.g: -

"this or "that or" or "this or that'"

It will replace or for the above strings also. If you want it not to replace in the above case, you can change the regex to: -

str = str.replaceAll("or(?=(?:[^"']*("|')[^"']*\1)*[^"']*$)", "||");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...