我想从字符串中删除所有特殊字符,而不是特殊字符。 例如,像Sund @ y,He !! o,^ stars,creat!vity
这样的词我发现很多关于删除特殊字符的正则表达式但不能创建具有特殊字符单词的正则表达式。
String example = "This is Sund@y."
预期产出:
result : This is
答案 0 :(得分: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
答案 1 :(得分:0)
就个人而言,我会选择一个简单的单行程序,不需要你手动执行字符串拼接:
String result = target.replaceAll("[^ ]*\\p{Punct}[^ ]*", "");
注意双反斜杠 - 因为我们需要在字符串中表示单个反斜杠(以生成正则表达式标记\p{Punct}
),我们必须转义反斜杠。
答案 2 :(得分:-1)
试试这个。
String example = "This is Sund@y." ;
String result = Stream.of(example.split("\\s+"))
.peek(s -> System.out.println(s))
.filter(w -> !w.matches(".*\\W.*"))
.collect(Collectors.joining(" "));