Python - re.findall returns unwanted result

2019-01-07 00:46发布

re.findall("(100|[0-9][0-9]|[0-9])%", "89%")

This returns only result [89] and I need to return the whole 89%. Any ideas how to do it please?

3条回答
太酷不给撩
2楼-- · 2019-01-07 01:01

The trivial solution:

>>> re.findall("(100%|[0-9][0-9]%|[0-9]%)","89%")
['89%']

More beautiful solution:

>>> re.findall("(100%|[0-9]{1,2}%)","89%")
['89%']

The prettiest solution:

>>> re.findall("(?:100|[0-9]{1,2})%","89%")
['89%']
查看更多
Summer. ? 凉城
3楼-- · 2019-01-07 01:11
>>> re.findall("(?:100|[0-9][0-9]|[0-9])%", "89%")
['89%']

When there are capture groups findall returns only the captured parts. Use ?: to prevent the parentheses from being a capture group.

查看更多
趁早两清
4楼-- · 2019-01-07 01:16

Use an outer group, with the inner group a non-capturing group:

>>> re.findall("((?:100|[0-9][0-9]|[0-9])%)","89%")
['89%']
查看更多
登录 后发表回答