Python - re.findall返回不需要的结果

时间:2021-12-10 03:15:59
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?

这只返回结果[89],我需要返回整个89%。有什么想法可以吗?

3 个解决方案

#1


6  

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

#2


10  

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

当有捕获组时,findall仅返回捕获的部分。使用?:防止括号成为捕获组。

#3


2  

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

使用外部组,内部组为非捕获组:

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

#1


6  

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

#2


10  

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

当有捕获组时,findall仅返回捕获的部分。使用?:防止括号成为捕获组。

#3


2  

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

使用外部组,内部组为非捕获组:

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