python - 在 Python 中使用 .find 查找第一个非数字字符

标签 python regex

我有一个包含 ABC 12345 的字符串还有ABC 98765.ABC 55555<

用于查找 ABC然后确定我使用的以下数字序列

index = page.find('ABC',index)
t1 = page.find(' ',index+1)
t2 = page.find(' ',t1+4)

这给了我 12345结果,但不是 9876555555 .

我如何更改第 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/

相关文章:

python - 尝试打开()文件时出现类型错误: 'newline' is an invalid keyword argument for this function,

python - 如何解决 "azure.common.AzureHttpError: This request is not authorized to perform this operation. ErrorCode: AuthorizationFailure"

python - 如何将代码升级到Django 2或在Django 1.9中使用类似 "path"的东西?

javascript - 浏览器对具有前瞻性的正则表达式的不同解释

regex - 在 sed 搜索/替换中访问匹配?

PHP 简单的正则表达式问题

python - 如何扭曲矩形对象以适应其较大的边界框

python - 如何将 dumbo 序列文件输入转换为制表符分隔的文本

python - 使用 python 和正则表达式从文本中提取

javascript - 匹配 101 - 999 的正则表达式模式