Jakub Turcovsky
Jakub Turcovsky

Reputation: 2126

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?

Upvotes: 6

Views: 736

Answers (4)

mcklmo
mcklmo

Reputation: 109

re.findall("/d+/%","89%")

d+ gets a number, regardless of how long.

Upvotes: 0

0x90
0x90

Reputation: 40982

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

Upvotes: 6

user707650
user707650

Reputation:

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

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

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361575

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

Upvotes: 11

Related Questions