使用正则表达式和 Java String.replaceAll()
方法时是否可以忽略分隔符?
例如:
String input_string = "test, testing, test";
String regex_expression = "(test)(,|$)";
String replace_expression = "foo";
String output_string = input_string.replaceAll(regex_expression, replace_expression)
- 当前结果:“foo 测试,foo”
- 期望结果:“foo,测试,foo”
我需要在正则表达式中搜索分隔符,但我想在替换时忽略它们。
最佳答案
您不断更改问题,但此答案适合当前版本。您可以使用前瞻断言来处理替换逻辑。
String input_string = "test, testing, test";
String output_string = input_string.replaceAll("test(?=,|$)", "foo");
实际上,我的答案与您已有的非常相似。唯一的区别是我使用的前瞻不使用逗号,而您似乎不希望这样做。
关于java - 忽略分隔符替换所有java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446968/