繁体   English   中英

在保留“笑脸”的同时从字符串中删除多余的标点符号?

[英]Remove extra punctuation from string while keeping “smileys”?

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

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

基本上,我想从输入字符串中删除标点符号,例如-(。,:;等),然后将其替换为空字符串。 但我想保留表情符号-:)或:(。我编写了以下代码,但无法正常工作。

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

谢谢。

尝试这样的事情:

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

快速分解:

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

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

我在JavaScript中对此进行了测试:

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

因此,这将转化为Java中的其中一种

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

您可以尝试以下方法:

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

结果

:( :) 你今天好吗 :(

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM