使用正则表达式从字符串中删除字符
Remove chars from string using Regular Expression
给定一个字符串数组,其中包含字母数字字符以及必须删除的标点符号。例如字符串 x="0-001" 被转换为 x="0001"。
为此我有:
punctuations = list(string.punctuation)
其中包含必须从字符串中删除的所有字符。我正在尝试使用 python 中的正则表达式解决此问题,关于如何继续使用正则表达式的任何建议?
import string
punctuations = list(string.punctuation)
test = "0000.1111"
for i, char in enumerate(test):
if char in punctuations:
test = test[:i] + test[i+ 1:]
如果您只想从字符串中删除非字母数字字符,只需使用 re.sub
:
即可
>>> re.sub('\W', '', '0-001')
'0001'
注意,\W
将匹配任何非 Unicode 单词字符的字符。这与\w
相反。对于 ASCII 字符串,它等同于 [^a-zA-Z0-9_]
.
给定一个字符串数组,其中包含字母数字字符以及必须删除的标点符号。例如字符串 x="0-001" 被转换为 x="0001"。
为此我有:
punctuations = list(string.punctuation)
其中包含必须从字符串中删除的所有字符。我正在尝试使用 python 中的正则表达式解决此问题,关于如何继续使用正则表达式的任何建议?
import string
punctuations = list(string.punctuation)
test = "0000.1111"
for i, char in enumerate(test):
if char in punctuations:
test = test[:i] + test[i+ 1:]
如果您只想从字符串中删除非字母数字字符,只需使用 re.sub
:
>>> re.sub('\W', '', '0-001')
'0001'
注意,\W
将匹配任何非 Unicode 单词字符的字符。这与\w
相反。对于 ASCII 字符串,它等同于 [^a-zA-Z0-9_]
.