【发布时间】:2021-06-14 07:49:39
【问题描述】:
用例:
输入:“___Test_String”
输出:“XXXTest_String”
我想用 X 替换所有开始的下划线。 每个下划线的 catch 应替换为相应的 X。
条件:
字符串可能以下划线开头,也可能不以下划线开头。如果它不以下划线开头,则保持原样。
我试过了:
replaceAll("[_]","X") = XXXTestXString - It replaced all the underscores.
replaceAll("^[_]+","X") = XTestXString - Replaced all the starting underscores with a single X.
replaceFirst("_","X") = X__Test_String - Just replaced the first underscore.
我知道使用非正则表达式方法很容易实现,但如果可能的话,我想要一个正则表达式解决方案。
任何帮助将不胜感激。
【问题讨论】:
-
您的最后一次通话工作正常,您只是使用了 replaceFirst 而不是 replaceAll。
-
好吧,不,使用 replaceAll("_","X") 也会替换中间的下划线。如上所述,这不是我想要的。
-
我看错了帖子。下面发布的解决方案应该可以正常工作。
标签: java regex replaceall