Java字符串替换所有正则表达式
您好,我想删除长字符串中的某些单词,问题是有些单词以“s”结尾,有些以大写字母开头,基本上我想转到:Java字符串替换所有正则表达式,java,regex,replace,Java,Regex,Replace,您好,我想删除长字符串中的某些单词,问题是有些单词以“s”结尾,有些以大写字母开头,基本上我想转到: “你好猫猫狗狗狐狸狐狸狐狸” 进入: “你好” 目前我有此代码,但我想对其进行改进,提前感谢: .replace("foxs", "") .replace("Fox", "") .replace("Dogs", "") .replace(
“你好猫猫狗狗狐狸狐狸狐狸”
进入:
“你好”
目前我有此代码,但我想对其进行改进,提前感谢:
.replace("foxs", "")
.replace("Fox", "")
.replace("Dogs", "")
.replace("Cats", "")
.replace("dog", "")
.replace("cat", "")
试试这个:
String input = "Hello cat Cats cats Dog dogs dog fox foxs Foxs";
input = input.replaceAll("(?i)\\s*(?:fox|dog|cat)s?", "");
也许你可以尝试匹配除“你好”之外的所有单词。 比如:
string.replaceAll("(?!Hello)\\b\\S+", "");
String str = "Hello cat Cats cats Dog dogs dog fox foxs Foxs";
Pattern p = Pattern.compile("fox[s]?|dog[s]?|cat[s]?", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
String result = m.replaceAll("");
System.out.println(result);
您可以在中进行测试
这样做的目的是对
Hello
word执行一个消极的前瞻,并让其他单词出现 您可以生成与单词的所有组合相匹配的模式。也就是说,对于狗
您需要图案[Dd]ogs?
:
是匹配两种情况的字符类[Dd]
匹配零或一个s?
s
- 单词的其余部分将区分大小写。也就是说,
将不匹配狗
public static void main(String[] args) {
// it's easy to add any other word
String original = "Hello cat Cats cats Dog dogs dog fox foxs Foxs";
String[] words = {"fox", "dog", "cat"};
String tmp = original;
for (String word : words) {
String firstChar = word.substring(0, 1);
String firstCharClass = "[" + firstChar.toUpperCase() + firstChar.toLowerCase() + "]";
String patternSrc = firstCharClass + word.substring(1) + "s?"; // [Ww]ords?
tmp = tmp.replaceAll(patternSrc, "");
}
tmp = tmp.trim(); // to remove unnecessary spaces
System.out.println(tmp);
}
因此,您可以预先编译所需单词的列表,并使其不区分大小写,例如:
string.replaceAll("(?!Hello)\\b\\S+", "");
String str = "Hello cat Cats cats Dog dogs dog fox foxs Foxs";
Pattern p = Pattern.compile("fox[s]?|dog[s]?|cat[s]?", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
String result = m.replaceAll("");
System.out.println(result);
[s] ??如果有复数形式,则处理在哪里?字符将匹配0或1使用不区分大小写的标志
(?i)
和(?i)\s(?:fox | dog | cat)s
我将删除一个\\s*
,否则foo cat bar
将变成foobar
,而不是(我猜首选)foo bar
@Pshemo是的。。。在我发布之前大约30秒,评论者的Jovan留下了一个精彩而完美的模式。是的,写包含完全可执行代码的答案比只写解决方案花费更多的时间:)其中一个\\b
是多余的。是的,你是对的。我编辑答案并删除其中一个,这样你就不必把它放在里面了。如果您希望匹配结尾处的一组字符或字符范围,则情况会更为严重。[0-9]
或[s|es]
。我同意这并不一定清楚。所以它可能只是:Pattern.compile(“foxs?| dogs?| cats?”,Pattern.CASE|u不区分大小写)代码>很好,你意识到s?
和[s]?
将以同样的方式工作(IMO添加[
]
会让人更难理解,特别是对于刚加入regex的人来说,但这是个人偏好的问题)。除此之外,“或[s|es]
”看起来不像是合适的示例(或者您误解了它),因为[…]
只能匹配[…]
中定义的字符集中的单个字符。所以[s|es]
只能匹配s
或
或e
(第二次放置s
不会改变任何内容)。有效点。在我的第二个例子中,它应该是(s | es),我确实同意它确实使它更难理解,总是有改进的余地