Strange Behaviour of replaceAll method of String

2019-08-11 08:55发布

I am facing strange behaviour of replaceAll method of String class.

I have a string buffer which contain below data

keyRPT1={keyRPT11=01|keyRPT19=01}|keyRPT3={keyRPT11=03|keyRPT19=01}|keyRPT8={keyRPT11=08|keyRPT19=01}

i write below code to replace the "keyRPT11=08|keyRPT19=01" with "keyRPT11=08|keyRPT19=2"

i am using below code for that

String complementaryInformation = "keyRPT1={keyRPT11=01|keyRPT19=01}|keyRPT3={keyRPT11=03|keyRPT19=01}|keyRPT8={keyRPT11=08|keyRPT19=01}";

complementaryInformation = complementaryInformation.replaceAll("keyRPT11=08|keyRPT19=01","keyRPT11=08|keyRPT19=2");

replaceAll give me the unexpected output

keyRPT1={keyRPT11=01|keyRPT11=08|keyRPT19=2}|keyRPT3={keyRPT11=03|keyRPT11=08|keyRPT19=2|keyRPT8={keyRPT11=08|keyRPT19=2|keyRPT11=08|keyRPT19=2}

when i am using replace method then i'll get the right output

keyRPT1={keyRPT11=01|keyRPT19=01}|keyRPT3={keyRPT11=03|keyRPT19=01}|keyRPT8={keyRPT11=08|keyRPT19=2}

Any idea guys??

2条回答
叼着烟拽天下
2楼-- · 2019-08-11 09:18

String.replaceAll() takes a regular expression, whereas String.replace() takes a literal.

查看更多
Summer. ? 凉城
3楼-- · 2019-08-11 09:32

You need to escape the | symbol which has special meaning in regex.

complementaryInformation = complementaryInformation.replaceAll("keyRPT11=08\\|keyRPT19=01","keyRPT11=08|keyRPT19=2");

replaceAll() method takes regex pattern as first parameter. replace() method does not take regex as parameter.

查看更多
登录 后发表回答