[英]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 "|"
在字符串中使用“ OR”,但是由于某种原因,它用“ OR”替换每个空格,是“ |” 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 |
replaceAll
使用正则表达式语法和正则表达式|
is operator representing OR
operation which means that "||"
是代表“
OR
运算符的运算符,表示"||"
is interpreted as regex as: 被解释为正则表达式为:
""
OR ""
OR ""
- empty string OR empty String OR empty String ""
OR ""
OR ""
-空字符串或空字符串或空字符串
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. 但是为了避免这种混乱,您可以使用
replace
代替replaceAll
,这将为您进行转义。
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. replaceAll
函数使用正则表达式来匹配字符。 Since |
由于
|
is a special character in regex , you need to escape |
是regex中的特殊字符,您需要转义
|
symbol in the regex to match a literal |
正则表达式中的符号以匹配文字
|
symbol. 符号。
ans = ans.replaceAll("\\|", "OR");
This will replace every |
这将替换所有
|
symbol with OR
. 带有
OR
符号。
For two pipe symbols. 对于两个管道符号。
ans = ans.replaceAll("\\|\\|", "OR");
This will replace every two pipe symbols ||
这将替换每两个管道符号
||
with OR
与
OR
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.