简体   繁体   中英

How do I replace the '|' character in a string in java?

I have a weird problem in one of my programs, I simply want to replace every occurrence of "||" with "OR" in a string, but for some reason it replaces every blank space with "OR", is "|" some sort of escape character or something?

I've been using this statement to do it

ans = ans.replaceAll("||", "OR");

Does anyone know what's going on or how I can fix this?

replaceAll uses regex syntax and in regex | is operator representing OR operation which means that "||" is interpreted as regex as:

"" OR "" OR "" - empty string OR empty String OR empty String

If you want to change | into literal you need to escape it for instance by adding \\ before it (in string \\ needs to be written as "\\\\" ).

But to avoid this confusion you can use replace instead of replaceAll which will do escaping part for you.

So instead of

ans = ans.replaceAll("||", "OR");

simply use

ans = ans.replace("||", "OR");

您可以在第一个参数中使用不使用正则表达式的replace

ans = ans.replace("||", "OR");

replaceAll function uses regex to match characters. Since | is a special character in regex , you need to escape | symbol in the regex to match a literal | symbol.

ans = ans.replaceAll("\\|", "OR");

This will replace every | symbol with OR .

For two pipe symbols.

ans = ans.replaceAll("\\|\\|", "OR");

This will replace every two pipe symbols || with OR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM