Strange Behaviour of replaceAll method of String

2019-08-11 08:45发布

问题:

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??

回答1:

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.



回答2:

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