首页 > 解决方案 > 在 python 中使用正则表达式/替换替换文本中的字母数字

问题描述

我想删除文本中的字母数字字符。例如,我有如下文字:

text= I want to remove alphanumeric jhanb562nkk from the text. Remove alphanumeric from all the texts. uhufshfn76429 is very hard to figure out.

预期结果

result=I want to remove alphanumeric from the text. Remove alphanumeric from all the texts.  is very hard to figure out.

我不确定我们如何使用 regex/replace 方法从文本中删除它们。

标签: pythonregexreplace

解决方案


您可以使用以下正则表达式:
[A-Za-z]+[\d]+[\w]*|[\d]+[A-Za-z]+[\w]*

函数调用将是:
re.sub(rgx_str, '', text)

请注意,这将在清除字母数字文本的地方留下额外的空间。删除此问题的一种简单方法是运行另一个正则表达式以进行后处理:
" +"并替换为" ".


推荐阅读