[英]How to remove all special character in a string except dot and comma
我有一個包含許多特殊字符和文本的句子,我想刪除除點和逗號之外的所有特殊字符。
例如,這是什么:
[u' %$HI# Jhon, $how$ are *&$%you.%$
我正在嘗試生成以下字符串:
HI Jhon, how are you.
我試過這個
("[u' %$HI# Jhon, $how$ are *&$%you.%$").replaceAll("[^a-zA-Z]+","");
但它也刪除了逗號和點。 我想要逗號和點在那里。
最后我找到了解決方案:
Python:
import re
my_str = "[u' %$HI# Jhon, $how$ are *&$%you.%$"
my_new_string = re.sub('[^.,a-zA-Z0-9 \n\.]', '', my_str)
print (my_new_string)
爪哇:
("[u' %$HI# Jhon, $how$ are *&$%you.%$").replaceAll("[^ .,a-zA-Z0-9]");
謝謝大家。 我不知道我的問題有什么問題,沒有自由提問。 :-(
("[u' %$HI# Jhon, $how$ are *&$%you.%$").replace(/[^.,a-zA-Z]/g, '');
你需要在括號內添加逗號和點,就像我剛剛做的那樣。
您可能也想包含數字。
("[u' %$HI# Jhon, $how$ are *&$%you.%$").replace(/[^.,a-zA-Z0-9]/g, '');
已編輯
而且,如下所述,您的輸出也需要空格:
("[u' %$HI# Jhon, $how$ are *&$%you.%$").replace(/[^.,a-zA-Z ]/g, '');
這也可能有幫助:
>>> punctuation = """!\"#$%&'()*+-/:;<=>?@[\\]^_`{|}~"""
>>> string = "[%$HI# Jhon, $how$ are *&$%you.%$"
>>> edited = ""
>>> for i in string:
... if i not in punctuation:
... edited += i
...
>>> edited
'HI Jhon, how are you.'
使用 lambda [java]組裝一個沒有“特殊”字符的新字符串
String s = "[u' %$HI# John, $how$ are *&$%you.%$";
s.codePoints().mapToObj( Character::toChars ).filter(
a -> (a.length == 1 && (Character.isLetterOrDigit( a[0] ) || Character.isSpaceChar( a[0] )
|| a[0] == '.' || a[0] == ',')) )
.collect( StringBuilder::new, StringBuilder::append, StringBuilder::append ).toString();
//u HI John, how are you.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.