首页 > 解决方案 > 如何删除Java文件中特定单词的结尾?

问题描述

我想删除文件中所有单词的结尾,例如删除所有 -ed(工作、爱、毁、Photoshopped、操纵)到(工作、爱、毁、Photoshopp、操纵)

我不知道该怎么做,我正在寻找正则表达式语法,但我得到的是最后只删除一个符号

 aLine = aLine.replaceAll("[\\<ed>]\\b", "");

输入是:

坐在家里的打字机前用photoshop处理

我有:

坐在 hom worke photoshoppe 的打字机前

最简单的方法是什么?

标签: javaregexfile

解决方案


我建议使用以下正则表达式:

(?<=\w)ed\b

演示

说明:

  • (?<=\w)(?<=[a-zA-Z])强制在 的左侧有一个单词字符ed,或一个字母(限制它是单词的一部分)
  • \b强制该字符后跟一个单词边界字符

然后将其调整为您的代码:

String input="I have worked a lot and ruined my health but I have loved my job even if "
        + "I habe been manipulated and ruined by this Photoshopped picture. "
        + "Ed and Eddy are happy today even if they have partied the whole night. ";

String output=input.replaceAll("(?<=\\w)ed\\b", "");
System.out.println(output);

输出:

I have work a lot and ruin my health but I have lov my job even if I habe been manipulat and ruin by this Photoshopp picture. Ed and Eddy are happy today even if they have parti the whole night. 

正则表达式快速入门表:http ://www.rexegg.com/regex-quickstart.html

概括

(?<=\w)[a-zA-Z]{2}\b

如果要删除所有单词的最后 2 个字母(输入字符串中的长度超过 2 个字符),可以使用此正则表达式

改进:

也可以删除后向并简单地使用以下正则表达式:\Bed\bfor ed-end words 并\B[a-zA-Z]{2}\b删除所有单词的最后 2 个字母(输入字符串中的长度超过 2 个字符)

感谢revo的改进!


推荐阅读