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

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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值