Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

python - using regex and capture groups in next method

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 first capture group to variable

    list = ['firstString','xxxSTATUS=100','thirdString','fourthString']
    value = next(x for x in list if [re.search('.*STATUS=(.*)', x)])
    

if I assign it to 'value' as it is, I get 'xxxSTATUS=100' (string type), BUT if I do it like so:

  value = next(x for x in list if [re.search('.*STATUS=(.*)', x).group(1)])

I get:

AttributeError: 'NoneType' object has no attribute 'group'

Obviously I can't do value.group(1) as it is string and not regex object. I also get (it is my assumption) that at the time I'm using regex pattern, my variable is still of no type,because it wasn't assigned yet.

So my question is how to solve this issue and assign capture group eg. '100' to variable. Is there any workaround?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...