使用Python中的.find()查找第一个非数字字符
我有一个字符串,里面包含了 ABC 12345
,还有 ABC 98765.
或者 ABC 55555<
为了找到 ABC
,然后识别后面的数字序列,我使用了
index = page.find('ABC',index)
t1 = page.find(' ',index+1)
t2 = page.find(' ',t1+4)
这样我得到了 12345
作为结果,但没有找到 98765
或 55555
。
我该如何修改第3行,才能找到空格和其他字符,比如 .
或 <
?
我尝试过
import re
t2 = re.search("\d", page,t1+4)
但是这个语法是错的。
1 个回答
6
使用正则表达式来查找紧跟在字面文本 ABC
后面的数字,后面可以有可选的空格:
match = re.search(r'ABC\s*(\d+)', page)
if match:
print match.group(1)
这个方法不管数字后面跟着什么都能工作:
>>> re.search(r'ABC\s*(\d+)', 'ABC 98765.').group(1)
'98765'
>>> re.search(r'ABC\s*(\d+)', 'ABC 55555<').group(1)
'55555'
如果你需要找到多个匹配项,可以使用 findall()
方法:
matches = re.findall(r'ABC\s*(\d+)', page)
这样你就能得到一个包含所有跟在字面文本 ABC
后面的数字组的列表:
>>> re.findall(r'ABC\s*(\d+)', 'Some text with ABC 98765. There is some other text too, with ABC 55555<!')
['98765', '55555']