【问题标题】:Java string replaceAll regexJava字符串replaceAll正则表达式
【发布时间】:2018-02-28 15:45:21
【问题描述】:

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

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

进入:

"Hello"

目前我有此代码,但我想对其进行改进,在此先感谢:

                    .replace("foxs", "")
                    .replace("Fox", "")
                    .replace("Dogs", "")
                    .replace("Cats", "")
                    .replace("dog", "")
                    .replace("cat", "")

【问题讨论】:

  • 使用不区分大小写的标志 (?i)(?i)\s(?:fox|dog|cat)s?

标签: java regex replace


【解决方案1】:

试试这个:

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

Demo

【讨论】:

  • 我会删除一个\\s*,否则foo cat bar 会变成foobar 而不是(我猜是首选)foo bar
  • @Pshemo 是的,你是对的......评论者 S Jovan 在我发帖前大约 30 秒留下了一个完美无瑕的图案。
  • 是的,编写包含完全可执行代码的答案比仅编写解决方案需要更多时间:)
【解决方案2】:

也许您可以尝试匹配除单词Hello 之外的所有内容。 比如:

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

您可以在this link 进行测试。

这个想法是对Hello 单词执行否定前瞻,并让任何其他单词出现。

【讨论】:

  • \\b 之一是多余的。
  • 是的,你是对的。我编辑答案并删除其中一个。
【解决方案3】:

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

  • [Dd] 是匹配这两种情况的字符类
  • s? 匹配零或一 s
  • 单词的其余部分将区分大小写。 IE。 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);
}

【讨论】:

    【解决方案4】:

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

        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

    【讨论】:

    • 所以你不必把它放在里面。如果您想匹配末尾的一组字符或字符范围[0-9][s|es],则更是如此。我同意这不一定很清楚。所以它可能只是:Pattern.compile("foxs?|dogs?|cats?", Pattern.CASE_INSENSITIVE);
    • 很高兴您意识到s?[s]? 将以相同的方式工作(IMO 添加[ ] 使其更难理解-尤其是对于正则表达式的新手-但那是个人喜好问题)。除了那个“或[s|es]”看起来不像是正确的例子(或者你误解了它),因为[...]只能匹配[...]中定义的字符集中的单个字符。所以[s|es] 只能匹配s|e(第二次输入s 不会在这里改变任何东西)。
    • 有效积分。在我的第二种情况下,它应该是(s|es),我同意它确实使理解变得更加困难,总是有改进的余地
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多