2

How can i replace String AXA || BXB && CXC || BXB to AXA OR BXB && CXC OR BXB ?

i tried

expression = "AXA || BXB && CXC || BXB";
expression = expression.replaceAll("||", " OR ");

But this doesnt provide desired result ie AXA OR BXB && CXC OR BXB

4

6 回答 6

4

不要使用正则表达式,replace而是尝试使用例程

expression = "AXA || BXB && CXC || BXB";
expression = expression.replace("||", " OR ");
于 2012-09-03T16:19:00.697 回答
1

replaceAll使用正则表达式,并且|是一个特殊字符,表示交替。因此,您需要转义它才能使用文字|

String s = "AXA || BXB && CXC || BXB";
System.out.println(s.replaceAll("\\|\\|", "OR"));

或者更好的是,只需使用replace(),它不使用正则表达式:

String s = "AXA || BXB && CXC || BXB";
System.out.println(s.replace("||", "OR"));
于 2012-09-03T16:18:24.590 回答
1

replaceAll将正则表达式作为第一个参数,请尝试使用replace

于 2012-09-03T16:18:48.667 回答
0

It's easy to forget what all the special characters are in regular expressions. I'm now in the habit of using String Pattern.quote(String s) around any literal I want to include that has any non-alphanumeric characters in it.

(If this case is as simple as you describe, I agree that replace() is the better choice.)

于 2012-09-03T16:28:50.277 回答
0

没有理由在String#replaceAll()这里使用,它将模式视为正则表达式。使用String#replace()并且您不必担心转义模式中的特殊字符

expression = "AXA || BXB && CXC || BXB";
expression = expression.replace("||", " OR ");
于 2012-09-03T16:19:24.560 回答
0

你需要逃离|

String expression = "AXA || BXB && CXC || BXB";
expression = expression.replaceAll(" ?\\|\\| ?", " OR ");
System.out.println(expression);

印刷

AXA OR BXB && CXC OR BXB
于 2012-09-03T16:19:27.387 回答