正则表达式从python中的文本中识别固定字符字母数字单词

正则表达式从python中的文本中识别固定字符字母数字单词,python,regex,Python,Regex,我有一个文本文件,试图从中删除七个字符的字母数字单词 Text1: " I have to remove the following word, **WORD123**, from the text given" Text2: " I have to remove the following word, **WORD001**, the text given" 到目前为止,我尝试了'\b[A-Za-z0-9]\b',但它不起作用 此外,我们是否可以添加一

我有一个文本文件,试图从中删除七个字符的字母数字单词

Text1: " I have to remove the following word, **WORD123**, from the text given"
Text2: " I have to remove the following word, **WORD001**, the text given"
到目前为止,我尝试了
'\b[A-Za-z0-9]\b'
,但它不起作用


此外,我们是否可以添加一个功能,使其只选择那些以“from”结尾的单词(不是实际单词,只是一个示例)。在上面的示例中,它应该只选择
WORD123
,而不选择
WORD001
,因为后面的一个单词不会以
from
结尾。您可以在这里使用
re.sub
,例如

inp = "I have to remove the following word, WORD123, FROM the text given"
out = re.sub(r'\s*\b[A-Za-z0-9]{7}\b[^\w]*(?=\bfrom)', '', inp, flags=re.IGNORECASE)
print(out)
这张照片是:

I have to remove the following word,from the text given

请注意,上面的正则表达式替换与您给出的第二个示例输入句子不匹配/不影响,因为7个字母的单词缺少关键字
from
作为下一个单词。

感谢您的解决方案,它可以工作。您是否也可以将“From”更改为区分大小写?@user10136853只需在
re.sub
调用中添加一个标志,即可在不区分大小写的模式下运行它,请参考上面我的更新答案。