在 Python 中删除字符串中以数字开头并包含句点的单词的最佳方法是什么?
this_string = 'lorum3 ipsum 15.2.3.9.7 bar foo 1. v more text 46 2. here and even more text here v7.8.989'
如果我使用正则表达式:
re.sub('[0-9]*\.\w*', '', this_string)
结果将是:
'lorum3 ipsum bar foo v more text 46 here and even more text here v'
我希望单词 v7.8.989
不会被删除,因为它是以字母开头的。
如果删除的单词没有添加不需要的空间,那就太好了。我上面的正则表达式代码仍然增加了空间。
最佳答案
您可以使用此正则表达式来匹配要删除的字符串:
(?:^|\s)[0-9]+\.[0-9.]*(?=\s|$)
它匹配:
(?:^|\s)
: 字符串或空格的开头[0-9]+
: 至少一位数\.
: 句号[0-9.]*
: 一些数字和句点(?=\s|$)
:断言字符串或空格结尾的前瞻Regex demo
然后您可以用空字符串替换任何匹配项。在 python 中
this_string = 'lorum3 ipsum 15.2.3.9.7 bar foo 1. v more text 46 2. here and even more text here v7.8.989 and also 1.2.3c as well'
result = re.sub(r'(?:^|\s)[0-9]+\.[0-9.]*(?=\s|$)', '', this_string)
输出:
lorum3 ipsum bar foo v more text 46 here and even more text here v7.8.989 and also 1.2.3c as well
https://stackoverflow.com/questions/74010703/