gpt4 book ai didi

python - 在 python 中编写正则表达式

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:23 25 4
gpt4 key购买 nike

我不擅长编写正则表达式,所以我需要一些帮助。我需要一个匹配 section 7.01(a)

的正则表达式

基本上 section 后面可以跟任何数字,例如 6.1/7.1/2.1

例子:

SECTION 7.01. Events of Default. If any of the following events
("Events of Default") shall occur:
(a) any Borrower shall fail to pay any principal of any Loan when and
as the same shall become due and payable, whether at the due date thereof
or at a date fixed for prepayment thereof or otherwise;

我正在尝试编写一个正则表达式,它可以给我包含这些的组

第 1 组

SECTION 7.01. Events of Default. If any of the following events
("Events of Default") shall occur:

第 2 组

(a) any Borrower shall fail to pay any principal of any Loan when and
as the same shall become due and payable, whether at the due date thereof
or at a date fixed for prepayment thereof or otherwise;

(a)之后还可以有更多的点,比如b等。

请帮我写一个正则表达式。

最佳答案

您可以使用以下方法,但是,要进行多个假设。节标题必须以 SECTION 开头,以冒号 : 结尾。其次,小节必须以匹配的括号'开始,并以分号结束。

import re
def extract_groups(s):
sanitized_string = ''.join(line.strip() for line in s.split('\n'))
sections = re.findall(r'SECTION.*?:', sanitized_string)
sub_sections = re.findall(r'\([a-z]\).*?;', sanitized_string)
return sections, sub_sections

示例输出:

>>> s = """SECTION 7.01. Events of Default. If any of the following events
("Events of Default") shall occur:
(a) Whether at the due date thereof
or at a date fixed for prepayment thereof or otherwise;

(b) Test;
SECTION 7.02. Second section:"""
>>> print extract_groups(s)
(['SECTION 7.01. Events of Default. If any of the following events("Events of Default") shall occur:', 'SECTION 7.02. Second section:'],
['(a) Whether at the due date thereofor at a date fixed for prepayment thereof or otherwise;', '(b) Test;'])

关于python - 在 python 中编写正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39403156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com