简体   繁体   中英

Python - re.findall returns unwanted result

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?

>>> 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.

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%']

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

>>> re.findall("((?:100|[0-9][0-9]|[0-9])%)","89%")
['89%']
re.findall("/d+/%","89%")

d+ gets a number, regardless of how long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM