java - 使用正则表达式(全局)替换特定单词 - Java

标签 java regex textpad

我试图想出一个正则表达式来替换特定的单词,无论位置/顺序如何,但它似乎不起作用

输入示例:

This is a a an the a the testing

正则表达式:

(\sa\s)|(\san\s)|(\sthe\s)

实际输出:

This is a the the testing

预期输出:

This is testing

最佳答案

您的正则表达式无法匹配某些 aanthe子串,主要是因为重叠匹配。即在这个字符串 foo an an an 中,上面的正则表达式将匹配第一个 <space>an<space> ,并且它不会匹配第二个 an因为第一个匹配项也会占用第二个 an 之前退出的空间。

string.replacaAll("\\s(?:an|the|a)(?=\\s)", "");

DEMO

如果任何一个字符串出现在最后,上面的正则表达式将会失败。在这种情况下,你可以使用这个,

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/

相关文章:

java - 使用ScalaTest测试包含@Autowired和私有(private)字段的java

java - 如何在Java中使用非标准采样因子缩放JPEG图像?

python - 为什么我的正则表达式对来自 file.read() 的输入不起作用?

javascript - 我想使用 JavaScript 从路径中删除文件名

regex - 如何在 Notepad++ 或 Textpad 中用正则表达式替换两个短语之间的所有文本?

TextPad:如何停止自动重新加载时的蜂鸣声

java - 我们可以使用来自android的数据通过Javascript在webview中显示它吗?

Java正则表达式,查找里面的文本

windows - TextPad 和 Unicode : full support?

java - java中时间戳字符串转时间戳