Python - re.findall returns unwanted result

萝らか妹 提交于 2019-11-26 12:33:37

问题


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?


回答1:


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:


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




回答3:


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

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


来源:https://stackoverflow.com/questions/16045643/python-re-findall-returns-unwanted-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!