正则表达式替换不在引号内的字符串(单引号或双引号) [英] Regex to replace a string not within quotes (single or double)
问题描述
我有一个输入字符串
this或that or或'this or that'
this or "that or" or 'this or that'
应转换为
this || 那或|| 这或那个
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(" || ")
输出
this || 那或|| '这||那个'
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.
推荐答案
试试这个正则表达式: -
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);
输出: -
this || "that or" || 'this or that'
上述正则表达式也将取代或
,如果您与和
'
不匹配。
The above regex will also replace or
, if you have a mismatch of "
and '
.
例如: -
"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)*[^\"']*$)", "||");
这篇关于正则表达式替换不在引号内的字符串(单引号或双引号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!