【问题标题】:How can I remove the special character words from a string?如何从字符串中删除特殊字符单词?
【发布时间】:2016-10-06 05:08:05
【问题描述】:

我想从字符串中删除所有特殊字符单词,而不是特殊字符。 例如,像 Sund@y、He!!o、^stars、creat!vity

这样的词

我发现很多关于删除特殊字符的正则表达式,但无法创建具有特殊字符单词的正则表达式。

String example = "This is Sund@y." 

预期输出:

result : This is

【问题讨论】:

  • 所以你想删除整个单词,而不仅仅是字符?
  • @MichaelPickett 是的,没错。
  • 查找带有特殊字符的单词并将其删除。有什么问题?
  • @Gaur93 - 你的评论对任何人有什么帮助?
  • @TheLostMind 我在问他在删除整个单词时遇到的问题。

标签: java regex string replace


【解决方案1】:

这可能对你有用:

public static void main(String[] args) {
    String yourString = " This is Sund@y.";
    String[] words = yourString.split("\\s+");
    String newWords = "";

    Pattern p = Pattern.compile("[@^!]");

    for (String word : words) {
        Matcher m = p.matcher(word);
        boolean b = m.find();
        if (b != true) {
            newWords += word + " ";
        }

    }
    System.out.println(newWords);
}

输入:This is Sund@y.
输出:This is

【讨论】:

    【解决方案2】:

    就我个人而言,我会选择一个不需要您手动执行字符串拼接的简单单行:

    String result = target.replaceAll("[^ ]*\\p{Punct}[^ ]*", "");
    

    注意双反斜杠 - 因为我们需要在字符串中表示单个反斜杠(生成正则表达式标记 \p{Punct}),所以我们必须转义反斜杠。

    【讨论】:

    • 完美运行。但是上一个查询中的正则表达式正在删除此函数之前的@y。
    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 2016-01-23
    相关资源
    最近更新 更多