我有一个包含 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)
但是这个语法被破坏了。
最佳答案
使用正则表达式查找跟在文字文本 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']
关于python - 在 Python 中使用 .find 查找第一个非数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15322171/