问题描述
我需要这方面的帮助:
- 我打开文件,使用 readlines 方法从中创建一个列表.
我需要找到第一次出现的模式/匹配并将第一个捕获组分配给变量
- I open file, use readlines method to create a list out of it.
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)])
如果我按原样将它分配给值",我会得到xxxSTATUS=100"(字符串类型),但如果我这样做:
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)])
我明白了:
AttributeError: 'NoneType' 对象没有属性 'group'
显然我不能做 value.group(1) 因为它是字符串而不是正则表达式对象.我也得到(这是我的假设),在我使用正则表达式模式时,我的变量仍然没有类型,因为它尚未分配.
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.
所以我的问题是如何解决这个问题并分配捕获组,例如.'100' 到变量.有什么解决方法吗?
推荐答案
AttributeError: 'NoneType' object has no attribute 'group'
错误只是意味着您没有匹配项并尝试访问组内容一个空对象.
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.
我认为最简单的方法是遍历搜索匹配项的列表项,一旦找到,获取第 1 组内容并将它们分配给 value
:
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)
注意你不需要模式中的初始 .*
因为 re.search
模式没有锚定在字符串的开头.
Note you do not need the initial .*
in the pattern as re.search
pattern is not anchored at the start of the string.
查看 Python 演示
另外,如果你想让你的初始方法起作用,你需要先检查是否有匹配 if re.search('STATUS=(.*)', x)
和然后再次运行它以使用 re.search('STATUS=(.*)', x).group(1)
:
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))
这篇关于python - 在下一个方法中使用正则表达式和捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!