我有一个场景,比如每当我得到像S00 B00这样的字符串替换为SOO BOO时,我的意思是用O替换零。我已将reg ex编写为standardName.replaceAll(" [A-Z] [00]"," OO")。但这也是删除字符S或B,我只得到OO。我需要输出SOO BOO。
答案 0 :(得分:2)
您可以捕获该字母并使用反向引用:
standardName = standardName.replaceAll("([A-Z])00","$1OO" );
甚至更安全的单词边界:
standardName = standardName.replaceAll("\\b([A-Z])00\\b","$1OO" );
或使用lookbehind:
standardName = standardName.replaceAll("\\b(?<=[A-Z])00\\b","OO" );