Strange Behaviour of replaceAll method of String

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 07:35: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??


回答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.



来源:https://stackoverflow.com/questions/7766692/strange-behaviour-of-replaceall-method-of-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!