String的replaceAll方法的奇怪行为 [英] Strange Behaviour of replaceAll method of String

查看:48
本文介绍了String的replaceAll方法的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正面临 String 类的 replaceAll 方法的奇怪行为.

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}

我编写下面的代码将"keyRPT11=08|keyRPT19=01"替换为"keyRPT11=08|keyRPT19=2"

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

我正在使用下面的代码

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 给我意想不到的输出

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}

有什么想法吗??

推荐答案

您需要对 | 符号进行转义,该符号在正则表达式中具有特殊含义.

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

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

replaceAll() 方法将正则表达式模式作为第一个参数.replace() 方法不以正则表达式为参数.

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

这篇关于String的replaceAll方法的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆