【问题标题】:regex - match punctuation at end of word in Java/Scala String正则表达式 - 匹配 Java/Scala 字符串中单词末尾的标点符号
【发布时间】:2015-01-01 22:20:02
【问题描述】:

我在这个链接上有这个正则表达式示例:http://regexr.com/39rr0

文字输入:
1. This camera support Monochrome, Neutral, Standard, Landscape and Portrait!

使用此正则表达式替换字符串时的预期输出:
1 This camera support Monochrome Neutral Standard Landscape and Portrait

我正在尝试删除单词后面的标点符号,所以我只得到没有它的单词。 我的正则表达式是(([\S]+)(,|:|;|\?|!)),它在那个正则表达式编辑器中匹配得很好。但是,当我执行string.replace( (([\S]+)(,|:|;|\?|!)), "") 甚至string.find( (([\S]+)(,|:|;|\?|!)) ) 时,它什么也找不到。

执行此操作的正则表达式是什么?我的正则表达式是否损坏或我使用不正确。

【问题讨论】:

    标签: java regex scala


    【解决方案1】:

    使用replaceAll,它适用于正则表达式

    System.out.println("This camera support Monochrome, Neutral, Standard, Landscape and Portrait!".replaceAll("([\\S]+)(,|:|;|\\?|!)", "$1"));
    

    打印:

    This camera support Monochrome Neutral Standard Landscape and Portrait
    

    【讨论】:

      【解决方案2】:

      使用\\p{P} 匹配所有标点符号。

      String str = "1. This camera support Monochrome, Neutral, Standard, Landscape and Portrait!";
      System.out.println(str.replaceAll("\\p{P}(?=\\s|$)", ""));
      

      输出:

      1 This camera support Monochrome Neutral Standard Landscape and Portrait
      

      说明:

      • \\p{P}匹配所有标点符号
      • (?=\\s|$) 仅当它后跟空格或行尾锚时。

      【讨论】:

        【解决方案3】:

        您不能使用String.replace,它只会替换文字。

        尝试更简单的PatternString.replaceAll

        System.out.println(
            "1. This camera support Monochrome, Neutral, Standard, Landscape and Portrait!"
            .replaceAll("\\p{Punct}", "")
        );
        

        输出

        1 This camera support Monochrome Neutral Standard Landscape and Portrait
        

        注意

        如果您只需要在单词字符(字母数字)之后替换标点符号,您可以改进Pattern

        "(?<=\\w)\\p{Punct}+"
        

        在你的情况下,它会产生相同的输出。

        【讨论】:

        • 你知道如何删除 .从标点符号?我有像 i.e. 这样的词,我想保持它们“原样”
        • @Adrian 您可以为此使用否定的外观,但是您将如何区分 "Portrait!"
        猜你喜欢
        • 2017-09-30
        • 2019-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        • 2016-12-22
        • 2014-03-24
        相关资源
        最近更新 更多