繁体   English   中英

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

[英]Regex to Identify Fixed character alphanumeric word from text in python

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

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作为下一个单词。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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