gpt4 book ai didi

Python - 如何删除以数字开头并包含句点的单词

转载 作者:行者123 更新时间:2023-12-05 09:01:10 24 4
gpt4 key购买 nike

在 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

关于Python - 如何删除以数字开头并包含句点的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74010703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com