在保持“表情符号”的同时从字符串中删除额外的标点符号?

时间:2012-03-19 21:33:54

标签: java regex

我使用正则表达式遇到了一些问题。你能帮帮我吗? 以下是我试图解决的问题 -

Input - :,... :(..:::))How are you today?..:(
Output - :( :) How are you today :(

基本上我想从输入字符串中删除标点符号,如 - (。,:; etc),并用空字符串替换它们。但我想保留表情符号 - :)或:(。我已经编写了以下代码,但它无效。

String s = ":,... :(..:::))How are you today?..:( ";  
Pattern pattern = Pattern.compile("^(\\Q:)\\E|\\Q:(\\E)(\\p{P}+)");  
Matcher matcher = pattern.matcher(s);    
s = matcher.replaceAll("");

谢谢。

3 个答案:

答案 0 :(得分:2)

尝试这样的事情:

[\p{P}&&[^:()]]|:(?![()])|(?<!:)[()]

快速分解:

[\p{P}&&[^:()]]    # any punctuation mark except ':', '(' and ')'
|                  # OR
:(?![()])          # a ':' not followed by '(' or ')'
|                  # OR
(?<!:)[()]         # a '(' or ')' not preceded by ':'

请注意,[ ... && [^ ... ]](set subtraction)对于Java的正则表达式实现是唯一的。请参阅:http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

答案 1 :(得分:1)

我在JavaScript中测试了这个:

[.,:;](?![)(])

因此,这将转换为Java中的其中一个

{Punct}(?![)(])
\\p{P}(?![)(])

答案 2 :(得分:1)

你可以试试这个:

    String s = ":,...:(..:::))How are you today?..:( ";  
    Pattern pattern = Pattern.compile("(:\\)|:\\(|[^\\p{Punct}]+|\\s+)");  
    Matcher matcher = pattern.matcher(s); 
    String res="";
    while(matcher.find()){
        res+=matcher.group(0);
    }
    System.out.println(res);

<强>结果

  

:( :)你今天好吗:(

相关问题