正则表达式替换不在引号内的字符串(单引号或双引号)

时间:2022-09-13 16:19:38

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.

问题是单引号中的字符串也被替换了。至于代码,样式只是一个例子。我会编译模式并在我开始工作时重用它。

1 个解决方案

#1


10  

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

#1


10  

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