0

In python, I have the following string:

"fish 14~ reel 14 rod B14"

I want to use REGEX to run through a for loop and return the location of each substring having one or more numbers in it. Ex.:

 For ():
     print location of substring

My expect output would be:

5
14
21

Please help, thanks.

ANSWER: Ok I tested all of the following and they all work. So which one is fastest? Drum roll.... In order from fastest to slowest: 1) Perreal - 9.7ms 2) Jon - 10.5ms 3) m.buettner - 12.3ms 4) upasana - 25.6ms

Thanks to all of you Python geniuses. There was another solution but I didn't test it. For various other reasons I chose Jon's method for my program.

4

4 回答 4

3

就像是:

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,那么您已经在可能的重复项中找到了答案...

于 2013-04-18T14:07:49.060 回答
0

尝试这个

import re

s =  "fish 14~ reel 14 rod B14" 

p = re.compile('[0-9]+')

a = p.findall(s)

print a

获得职位

for m in re.finditer(r'([a-zA-Z]+)?[0-9]+', s):
    st, en = m.span() 
    print "position ", st, en, " string ", s[st:en] 

你应该看到

位置 5 7 弦 14
位置 14 16 弦 14
位置 21 24 弦 B14

哪个是对的!

于 2013-04-18T14:12:57.387 回答
0

您也可以在不使用正则表达式的情况下执行此操作:

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

但这将为您提供不紧跟在另一个数字之前的数字的起始位置。向后弯曲以完成此操作:

p = list()
for i in [ i for i,c in enumerate(str) if c.isdigit() ]:
    if i > 0 and not str[i - 1].isdigit():
        while i > 0 and str[i - 1].isalnum():
            i -= 1
        p.append(i)
print p
于 2013-04-18T14:14:29.380 回答
0

尝试这个:

#!/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

输出:

5
14
21
于 2013-04-18T15:11:04.153 回答