我试图想出一个正则表达式来替换特定的单词,无论位置/顺序如何,但它似乎不起作用
输入示例:
This is a a an the a the testing
正则表达式:
(\sa\s)|(\san\s)|(\sthe\s)
实际输出:
This is a the the testing
预期输出:
This is testing
最佳答案
您的正则表达式无法匹配某些 a
或an
或the
子串,主要是因为重叠匹配。即在这个字符串 foo an an an
中,上面的正则表达式将匹配第一个 <space>an<space>
,并且它不会匹配第二个 an
因为第一个匹配项也会占用第二个 an
之前退出的空间。
string.replacaAll("\\s(?:an|the|a)(?=\\s)", "");
如果任何一个字符串出现在最后,上面的正则表达式将会失败。在这种情况下,你可以使用这个,
String test = "a an the an test is a success and an example";
System.out.println(test.replaceAll("\\s(?:an|the|a)(?=\\s|$)|^(?:an|the|a)(?=\\s)", "").trim());
输出:
test is success and example
关于java - 使用正则表达式(全局)替换特定单词 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29663404/