繁体   English   中英

查找以某个字符开头的行块

[英]Find blocks of lines starting with a certain character

文本:

Abcd
Aefg
bhij
Aklm
bnop
Aqrs

(注意,最后一行后面没有换行符)

Python代码:

print(re.findall('(^A.*?$)+',Text,re.MULTILINE))

这返回

['Abcd','Aefg','Aklm','Aqrs']

但是,我希望将相邻的行作为一组返回:

['Abcd\nAefg','Aklm','Aqrs']

我应该如何用 Python 解决这个问题?

您可以使用

((?:^A.*[\n\r]?)+)

请参阅regex101.com 上的演示 这是:

(
    (?:^A.*[\n\r]?)+ # original pattern 
                     # with newline characters, optionally
                     # repeat this as often as possible
)

Python

import re

data = """
Abcd
Aefg
bhij
Aklm
bnop
Aqrs"""

matches = [match.group(1).strip() 
           for match in re.finditer(r'((?:^A.*[\n\r]?)+)', data, re.M)]
print(matches)

哪个产量

['Abcd\nAefg', 'Aklm', 'Aqrs']

由于嵌套的量词,它最终可能导致灾难性的回溯。

您可以使用

re.findall(r'^A.*(?:\nA.*)*', text, re.M)

查看正则表达式演示

细节

  • ^ - 字符串的开头
  • A - A字母
  • .* - 线的rest
  • (?:\nA.*)* - 零个或多个重复
    • \nA - 换行符和A
    • .* - 该系列的 rest。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM