python - using regex and capture groups in next method

后端 未结 1 1284
日久生厌
日久生厌 2020-12-12 01:07

I need help with this one:

  1. I open file, use readlines method to create a list out of it.
  2. I need to find first occurrence of patern/match and assign

相关标签:
1条回答
  • 2020-12-12 01:28

    The AttributeError: 'NoneType' object has no attribute 'group' error just means you got no match and tried to access group contents of a null object.

    I think the easiest way is to iterate over the list items searching for the match, and once found, get Group 1 contents and assign them to value:

    import re
    list = ['firstString','xxxSTATUS=100','thirdString','fourthString']
    value = ""
    for x in list:
        m = re.search('STATUS=(.*)', x)
        if m:
            value = m.group(1)
            break
    
    print(value)
    

    Note you do not need the initial .* in the pattern as re.search pattern is not anchored at the start of the string.

    See the Python demo

    Also, if you want your initial approach to work, you need to check if there is a match first with if re.search('STATUS=(.*)', x), and then run it again to get the group contents with re.search('STATUS=(.*)', x).group(1):

    value = next(re.search('STATUS=(.*)', x).group(1) for x in list if re.search('STATUS=(.*)', x))
    
    0 讨论(0)
提交回复
热议问题