我正在尝试使用re.match选择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文档中找不到任何对我有帮助的信息。尝试使用python 2和3。
我怎么可能做错了
答案 0 :(得分:1)
使用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;
答案 1 :(得分:-1)
每个Python文档
re.match(模式,字符串,标志= 0)
如果字符串开始处的零个或多个字符与 正则表达式模式,返回相应的match对象。 如果字符串与模式不匹配,则返回None;否则返回false。请注意, 与零长度匹配不同。
因此,您可能应该使用re.search
或re.findall
答案 2 :(得分:-1)
re.match
从字符串的开头开始匹配,因此在字符串开头的(?<=...)
后面不匹配。如@Rakesh所述,请使用re.search