繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM