如何删除除逗号和逗号之外的字符串中的所有特殊字符

时间:2016-09-24 03:11:26

标签: java android

我有一个包含许多特殊字符和文字的句子,我想删除除点和逗号之外的所有特殊字符。

例如,这就是:

[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]");

谢谢大家。我不知道我的问题是什么错,没有自由要求。 : - (

3 个答案:

答案 0 :(得分:2)

("[u' %$HI# Jhon, $how$ are *&$%you.%$").replaceAll("[^.,a-zA-Z]");

你需要在括号内添加所有字符的逗号和点,就像我刚才那样。

你可能也希望包含数字。

("[u' %$HI# Jhon, $how$ are *&$%you.%$").replaceAll("[^.,a-zA-Z0-9]");

被修改

并且,如下所述,您的输出也需要空格:

("[u' %$HI# Jhon, $how$ are *&$%you.%$").replaceAll("[^.,a-zA-Z ]");

答案 1 :(得分:0)

这也可能有所帮助:

>>> 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.'   

答案 2 :(得分:0)

使用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.
相关问题