我正在尝试从单词classes之后的字符串中获取所有数字(或其变体)

Accepted for all the goods and services in classes 16 and 41.


预期输出:

16
41


我有多个遵循此模式的字符串,例如:

classes 5 et 30 # expected output 5, 30
class(es) 32,33 # expected output 32, 33
class 16        # expected output 5


到目前为止,这是我尝试过的操作:https://regex101.com/r/eU7dF6/3

(class[\(es\)]*)([and|et|,|\s]*(\d{1,}))+


但是我只能获取最后一个匹配的数字,即上述示例中的41

最佳答案

我建议使用classclasses / class(es)之后的数字获取所有子字符串,然后从这些数字中获取所有数字:

import re
p = re.compile(r'\bclass(?:\(?es\)?)?(?:\s*(?:and|et|[,\s])?\s*\d+)+')
test_str = "Accepted for all the goods and services in classes 16 and 41."
results = [re.findall(r"\d+", x) for x in p.findall(test_str)]
print([x for l in results for x in l])
# => ['16', '41']


IDEONE demo

由于不支持\G构造,也无法使用Python re模块访问捕获堆栈,因此无法使用您的方法。

但是,您可以像使用PyPi regex module一样进行操作。

>>> import regex
>>> test_str = "Accepted for all the goods and services in classes 16 and 41."
>>> rx = r'\bclass(?:\(?es\)?)?(?:\s*(?:and|et|[,\s])?\s*(?P<num>\d+))+'
>>> res = []
>>> for x in regex.finditer(rx, test_str):
        res.extend(x.captures("num"))
>>> print res
['16', '41']

关于python - 正则表达式:查找特定字符串后的所有数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35310343/

10-12 17:44
查看更多