Python - re.findall returns unwanted result

前端 未结 3 1967
栀梦
栀梦 2020-11-29 13:14
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

相关标签:
3条回答
  • 2020-11-29 14:07

    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%']
    
    0 讨论(0)
  • 2020-11-29 14:08
    >>> 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.

    0 讨论(0)
  • 2020-11-29 14:14

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

    >>> re.findall("((?:100|[0-9][0-9]|[0-9])%)","89%")
    ['89%']
    
    0 讨论(0)
提交回复
热议问题