python 如何在两个搜索之间打印行

6ljaweal  于 2023-06-28  发布在  Python
关注(0)|答案(1)|浏览(141)

我的文字如下:

FEATURE AAA cdslmd 22.02 28-jul-2023 1 \
3F76BA3DA7102935AD12 VENDOR_STRING=J:PERM DUP_GROUP=NONE \
vendor_info=13-jun-2023 \
ISSUER=CDNS2161b9360e2037d6f7bd35a11244661a ISSUED=13-jun-2023 \
EC0C" V7.1_LK=3F06FAFDD30D943EC2DD

FEATURE BBB cdslmd 22.02 28-jul-2023 2 7F061A2D977BFEF08F2F \
VENDOR_STRING=J:PERM DUP_GROUP=NONE vendor_info=13-jun-2023 \
ISSUER=CDNS2161b9360e2037d6f7bd35a11244661a ISSUED=13-jun-2023 \
A843" V7.1_LK=BFC68A9D5606A8296604

预期结果:

FEATURE AAA cdslmd 22.02 28-jul-2023 1 \
3F76BA3DA7102935AD12 VENDOR_STRING=J:PERM DUP_GROUP=NONE \
vendor_info=13-jun-2023 \
ISSUER=CDNS2161b9360e2037d6f7bd35a11244661a ISSUED=13-jun-2023 \
EC0C" V7.1_LK=3F06FAFDD30D943EC2DD

我的剧本:

import os
import re

pat1 = r"[A-Z]+.AAA"
pat2 = r"[^\\]$"

with open('all.txt') as f:
    match = False

    for l in f:
        if re.match(pat1, l): 
            match = True
            print (l) 
            continue
        if re.search(pat2, l): 
            match = False
            continue
        if match:
            print (l) 
f.close()

上述脚本的结果:

FEATURE AAA cdslmd 22.02 28-jul-2023 1 1F469A0DE7A48BDAE16B \

它只打印以pat1开头的一行。我想打印pat1pat2之间的行(其中pat1后面的行结尾不以“”结束)。

hc8w905p

hc8w905p1#

r"[^\\]$"将匹配每行末尾的换行符(\n)。你不需要正则表达式来进行检查,你可以简单地

if not l.strip().endswith('\\'): 
    match = False
    continue

此外,要获得所需的输出,即如果要打印不是以\结尾的那一行,你需要切换if语句的顺序:

if re.match(pat1, l):
            match = True
            print (l)
            continue
        if match:
            print (l)
        if not l.strip().endswith('\\'):
            match = False
            continue

或者,pattern2也可以是r"[^\\]\n$",但我觉得第一种方法更容易理解

相关问题