python重新匹配()未返回预期结果

2024-03-28 19:48:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用重新匹配地址:

revenue = "Revenue;;Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,190,140,1926,14,143;Coffee,325,19,293,1491,162;Water,682,14,852,56,659;Milk,829,140,609,120,87;;Expenses;;Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,120,65,890,54,430;Coffee,300,10,23,802,235;Water,50,299,1290,12,145;Milk,67,254,89,129,76;;"
revenue = re.match(r"(?<=Revenue;;).*(?=;E)", file_content)
print(revenue)

但是它返回None。你知道吗

我在regex101.com上测试了正则表达式,它提供了所需的匹配,即Revenue;;后面的文本和;Expenses前面的文本:

Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,190,140,1926,14,143;Coffee,325,19,293,1491,162;Water,682,14,852,56,659;Milk,829,140,609,120,87;

因此,我假设我的python实现有问题,但是,我在python regex文档中找不到任何帮助我的信息。在python2和python3上都试过了。你知道吗

我会做错什么


Tags: 文本地址itemcoffeewatermilkteaexpenses
3条回答

根据Python文档

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

所以您可能应该使用re.searchre.findall

使用re.search

例如:

import re

revenue = "Revenue;;Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,190,140,1926,14,143;Coffee,325,19,293,1491,162;Water,682,14,852,56,659;Milk,829,140,609,120,87;;Expenses;;Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,120,65,890,54,430;Coffee,300,10,23,802,235;Water,50,299,1290,12,145;Milk,67,254,89,129,76;;"
revenue = re.search(r"(?<=Revenue;;).*(?=;E)", revenue)
print(revenue.group())

输出:

Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,190,140,1926,14,143;Coffee,325,19,293,1491,162;Water,682,14,852,56,659;Milk,829,140,609,120,87;

re.match从字符串的开头开始匹配,因此字符串开头的(?<=...)后面的查找永远不会匹配。正如@Rakesh所提到的,使用re.search

相关问题 更多 >