[英]How can I remove the special character words from a string?
我想從字符串中刪除所有特殊字符,而不是特殊字符。 例如,像Sund @ y,He !! o,^ stars,creat!vity這樣的詞
我發現很多關於刪除特殊字符的正則表達式但不能創建具有特殊字符單詞的正則表達式。
String example = "This is Sund@y."
預期產量:
result : This is
這可能對你有用:
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
就個人而言,我會選擇一個簡單的單行程序,不需要您手動執行字符串拼接:
String result = target.replaceAll("[^ ]*\\p{Punct}[^ ]*", "");
注意雙反斜杠 - 因為我們需要在字符串中表示單個反斜杠(以生成正則表達式標記\\p{Punct}
),我們必須轉義反斜杠。
嘗試這個。
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(" "));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.