使用regex的多重选择

2024-09-24 02:19:14 发布

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

嗨,我有一个多模式需要提取。我的开始和结束标记是不同的组合。 它可以包含

ITEM 3              Quantitative and Qualitative Disclosures about Market Risk
As part of its Bank Credit  Agreement,  the Company was  required to purchase an
interest rate cap of $100 million for 
item 4 

也可以是

item 3.            Quantitative and Qualitative Disclosures about Market Risk
As part of its Bank Credit  Agreement,  the Company was  required to purchase an
interest rate cap of $100 million for 
item 4

也可以是

item 3a              Quantitative and Qualitative Disclosures about Market Risk
As part of its Bank Credit  Agreement,  the Company was  required to purchase an
interest rate cap of $100 million for 
item 4

我使用正则表达式作为

qaq =r"item[^a-zA-Z\n]*\d\s*\.\s*Quantitative and Qualitative Disclosures about Market Risk.*?item[^a-zA-Z\n]*\d\s*\.*"

我正在使用python。我的问题是我是否为每个模式编写了多个正则表达式,或者我是否可以在一个正则表达式中完成它。如果它可以在一个那么我如何实现这一点。你知道吗


Tags: andofasagreementitemmarketitsabout
2条回答

在正则表达式中,使用[^a-zA-Z\n]*匹配item和数字之间的内容。在本例中,我认为可以使用\s。你知道吗

一开始你有item 3item 3.item 3a。您可以使用\d\s*\.来匹配这3个变体,但这只会匹配3.

您可以在开头使用不区分大小写的标志来匹配item变体,或者指定不区分大小写的modifier(?i)并添加多行模式(?m)。你知道吗

^{}

细节

  • ^断言字符串的开头
  • item\s\d+匹配项,后跟空格字符和一个或多个数字
  • [a-z.]?\s+匹配可选的小写字符或后跟一个或多个数字的点
  • Quantitative and Qualitative Disclosures about Market Risk\n逐字匹配,后跟换行符
  • (?:.*\n)*?将任何字符重复零次或多次,然后换行,因为the dot does not match line breaks by default
  • item\s\d+匹配项、空格字符和一个或多个数字
  • $断言行尾

Demo Python

正则表达式:

^(?:ITEM|Item|item)\s\d[a-z]?\.?\s*Quantitative and Qualitative Disclosures about Market Risk(?:.*\n)*?item\s\d.*$

Demo

说明:

(?:ITEM|Item|item)-在各种情况下处理item的非捕获备用组。你知道吗

(?:.*\n)*?item\s\d.*$-任意数量字符的非捕获组,后跟\n,以惰性方式重复0到无限次*?,后跟小写item,后跟空格,后跟数字,后跟任意字符(0到无限),后跟行尾$

相关问题 更多 >