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

2
  • Are you actually trying to do the blind character substitution you specify here, or is this an attempt at parsing?
    – user395760
    Sep 3, 2012 at 16:18
  • 1
    raplaceAll uses a regex, and | is a special caracter, try doing string expression.replaceAll("\\|\\|", "OR");
    – Augusto
    Sep 3, 2012 at 16:19

6 Answers 6

4

Instead of using regular expressions, try the replace routine instead

expression = "AXA || BXB && CXC || BXB";
expression = expression.replace("||", " OR ");
2
  • @Pshemo, You're right, although underneath it still compiles a Pattern object. Otherwise StringUtils.replace(..) is a good alternative. Sep 3, 2012 at 16:27
  • You're right, it replace(char,char) escapes regex. I removed my previous comment since it was false info.
    – Pshemo
    Sep 3, 2012 at 16:30
1

replaceAll uses a regex, and | is a special character, which means alternation. Thus, you need to escape it in order to use a literal |:

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

Or better yet, just use replace(), which doesn't use a regex:

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

replaceAll takes a regular expression as its first argument, try using replace instead.

0

There's no reason to use String#replaceAll() here, which treats the pattern as a regex. Use String#replace() and you don't have to worry about escaping special characters in the pattern.

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

You need to escape out the |

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

prints

AXA OR BXB && CXC OR BXB
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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.