gpt4 book ai didi

java - 如何删除 Java 文件中单词的特定结尾?

转载 作者:搜寻专家 更新时间:2023-11-01 02:36:18 25 4
gpt4 key购买 nike

我想删除文件中单词的所有结尾,例如删除所有-ed (worked, loved, ruined, Photoshopped, manipulated) to (work, lov, ruin, Photoshopp, manipulat)

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

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

输入是:

Sitting at a typewriter at home worked photoshopped

我得到了:

Sitting at a typewriter at hom worke photoshoppe

最简单的方法是什么?

最佳答案

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

(?<=\w)ed\b

DEMO

解释:

  • (?<=\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\b对于 ed -结尾词和\B[a-zA-Z]{2}\b删除所有单词的最后 2 个字母(输入字符串中超过 2 个字符)

谢谢revo为了这个改进!

关于java - 如何删除 Java 文件中单词的特定结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50503338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com