Python正则表达式搜索所有包含一个或多个数字的子字符串的字符串

2024-05-21 03:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,我有以下字符串:

"fish 14~ reel 14 rod B14"

我想使用REGEX来运行for循环并返回每个子字符串中包含一个或多个数字的位置。例如:

 For ():
     print location of substring

我的预期产出是:

^{pr2}$

请帮忙,谢谢。在

回答: 好吧,我测试了下面所有的,它们都工作了。那么哪一个最快?打鼓。。。。按从最快到最慢的顺序: 1) 佩雷尔-9.7毫秒 2) 10.5米 3) m.buettner-12.3毫秒 4) upasana-25.6毫秒

感谢你们所有的Python天才。还有另一个解决方案,但我没有测试。出于各种其他原因,我选择了乔恩的方法作为我的计划。在


Tags: of字符串for顺序数字locationsubstringregex
3条回答

试试这个:

#!/usr/bin/env python

import re

str = "fish 14~ reel 14 rod B14"
index = 0
for x in str.split(" "):
    if re.search('\d', x):
        print(max(str.find(x), index))
    index += len(x) + 1

输出:

^{pr2}$

比如:

s =  "fish 14~ reel 14 rod B14"

import re

words = re.finditer('\S+', s)
has_digits = re.compile(r'\d').search
print [word.start() for word in words if has_digits(word.group())]
# [5, 14, 21]

所以,有效地找到单词开头的索引,然后检查每个单词是否有数字。。。在

如果最后一个条目应该是22而不是21,那么你已经在可能的副本中得到了你的答案。。。在

也可以在不使用regex的情况下执行此操作:

p = list()
for i in [ i for i,c in enumerate(str) if c.isdigit() ]:
    if len(p) == 0 or p[-1] + 1 != i:
        p.append(i)
print p

但这会给你一个数字的起始位置,而不是紧跟着另一个数字。向后弯曲以完成此操作:

^{pr2}$

相关问题 更多 >