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

在 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/

相关文章:

rust - Rust 中的一个可变借用或多个不可变借用……为什么?

regex - 删除换行符后跟多个选项卡正则表达式

ruby - 如何在 Ruby 中创建可调用属性

python - 在python中打印出两个列表的组合

c++ - 你能用折叠表达式实现 fn(x1 ^ fn(x0)) 吗?

r - 如何在组内创建字母序列?

c# - 在 C# 中将小驼峰命名法转换为 PascalCase?

go - gcloud 函数部署 go 运行时错误 "undefined: unsafe.Slice

c - 使用个性系统调用使堆栈可执行

c++ - 如何在 SSE2 中为 8 位和 16 位整数实现 vector 右移和左移?