Java字符串替换所有正则表达式

问题描述 投票:1回答:4

嗨,我想删除长字符串中的某些单词,问题是有些单词以“s”结尾,有些单词以大写字母开头,基本上我想转:

"Hello cat Cats cats Dog dogs dog fox foxs Foxs"

成:

"Hello"

目前我有这个代码,但我希望改进它,提前感谢:

                    .replace("foxs", "")
                    .replace("Fox", "")
                    .replace("Dogs", "")
                    .replace("Cats", "")
                    .replace("dog", "")
                    .replace("cat", "")
java regex replace
4个回答
3
投票

试试这个:

String input = "Hello cat Cats cats Dog dogs dog fox foxs Foxs";
input = input.replaceAll("(?i)\\s*(?:fox|dog|cat)s?", "");

Demo


2
投票

也许你可以尝试匹配除了Hello这个词之外的所有东西。就像是:

string.replaceAll("(?!Hello)\\b\\S+", "");

你可以在this link测试它。

这个想法是为Hello单词执行负向前瞻,并获得任何其他单词。


0
投票

您可以生成与单词的所有组合匹配的模式。即对于dog你需要模式[Dd]ogs?

  • [Dd]是一个匹配两种情况的字符类
  • s?匹配零或一个s
  • 其余部分将区分大小写。即dOGS不会是一场比赛。

这是你如何把它放在一起:

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);
}

0
投票

所以你可以预先编译你想要的单词列表,并使它不区分大小写:

    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

© www.soinside.com 2019 - 2024. All rights reserved.