[英]Python regex group() works, but findall() results are not as I expected
我正在解析一些日志,並想提取某種類型的所有參數名稱。 為了簡單起見,我將只包含一個小的子字符串。
log = 'WT.tz=-8&WT.bh=23&WT.ul=en-US'
#I want to find all strings that start with WT and get WT and all the following characters until I find an & or the end of the string. I tested this on an online regex page and it seems to work great.
regex = r'(?s)(?=WT).+?(?=(=))'
# if I try to find the first I get what I expected
re.search(regex,log).group()
>> 'WT.tz'
#when I try to find all I do not get what I thought I was going to get.
re.findall(regex,log)
>> ['=','=','=']
findall返回所有groups
。您有一個組(=)
。因此將其刪除。
regex = r'(?s)WT.+?(?==)'
^^^^^
同樣也不需要lookahead
。
輸出: ['WT.tz', 'WT.bh', 'WT.ul']
log = 'WT.tz=-8&WT.bh=23&WT.ul=en-US'
print(re.findall(r'WT\.[^&]*\b',log))
['WT.tz=-8', 'WT.bh=23', 'WT.ul=en-US']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.