【问题标题】:Regex to find text between expressions, where the end of one match might be the start of the next正则表达式在表达式之间查找文本,其中一个匹配的结尾可能是下一个匹配的开始
【发布时间】:2018-05-30 09:26:54
【问题描述】:

我想使用 Python 3.5 匹配以下数据中以“2 个电容器”、“1 个运算放大器”等开头的每行之间的文本:

#Sat Dec 16 09:10:37 2017
#
#2 capacitors:
#  0 c1 10 uF GND n1 
#  1 c2 47 pF nm nout 
#1 op-amp:
#  0 o1 lt1124 '+'=nin '-'=nm 'out'=nout a0=15M gbw=14.6 MHz 
#       un=2.7 nV/sqrt(Hz) uc=2.3 Hz in=300 fA/sqrt(Hz) ic=100 Hz 
#       umax=12 V imax=20 mA sr=4.5 V/us delay=18.9 ns 
#       pole at 200 kHz (real)        pole at 200 kHz (real)        zero at 800 kHz (real)        zero at 800 kHz (real)        zero at 9.4 MHz (real) 
#2 resistors:
#  0 r1 430 Ohm n1 nm
#  1 r2 43 kOhm nm nout
#4 nodes:
#  0 n1
#  1 nm
#  2 nout
#  3 nin
#Logarithmic frequency scale from 1 Hz to 100 kHz in 100 steps.

我要提取:

匹配 1(2, capacitors, # 0 c1 10 uF GND n1# 1 c2 47 pF nm nout)

匹配 2(1, op-amp, # 0 o1 lt1124 '+'=nin '-'=nm 'out'=nout a0=15M gbw=14.6 MHz# un=2.7 nV/sqrt(Hz) uc=2.3 Hz in=300 fA/sqrt(Hz) ic=100 Hz.......)

匹配 3(2, resistors, # 0 r1 430 Ohm n1 nm# 1 r2 43 kOhm nm nout)

匹配 4(4, nodes, # 0 n1# 1 nm# 2 nout# 3 nin)

第三组是否保留换行符对我来说并不重要。目前,我通过搜索第一个匹配项和第一行非空格之间的文本进行匹配:

^\#(\d+) (op\-amps|op\-amp|capacitors|capacitor|resistors|resistor|nodes|node):$([\d\D]*?)^#\S

regexr example

(必须启用MULTILINE 标志。[\d\D] 技巧是匹配不同平台上的所有字符,包括换行符。)

问题在于 1 op-amp4 nodes 段不匹配,因为它们是先前匹配的一部分:例如,#1 op-amp 行。如何获得所有可能的匹配项?

【问题讨论】:

    标签: python regex python-3.x match


    【解决方案1】:

    优化方案:

    import re
    
    with open('yourfile.txt') as f:
        pat = r'^#(\d+) (op-amps?|capacitors?|resistors?|nodes?):([\s\S]+?)(?=\n#\S+ )'
        result = re.findall(pat, f.read(), re.M)
        for m in result:
            print(m)
    

    输出:

    ('2', 'capacitors', '\n#  0 c1 10 uF GND n1 \n#  1 c2 47 pF nm nout ')
    ('1', 'op-amp', "\n#  0 o1 lt1124 '+'=nin '-'=nm 'out'=nout a0=15M gbw=14.6 MHz \n#       un=2.7 nV/sqrt(Hz) uc=2.3 Hz in=300 fA/sqrt(Hz) ic=100 Hz \n#       umax=12 V imax=20 mA sr=4.5 V/us delay=18.9 ns \n#       pole at 200 kHz (real)        pole at 200 kHz (real)        zero at 800 kHz (real)        zero at 800 kHz (real)        zero at 9.4 MHz (real) ")
    ('2', 'resistors', '\n#  0 r1 430 Ohm n1 nm\n#  1 r2 43 kOhm nm nout')
    ('4', 'nodes', '\n#  0 n1\n#  1 nm\n#  2 nout\n#  3 nin')
    

    详情:

    • <word>s?- 匹配零或一 s <word> 的结束字符
    • [\s\S]+? - 匹配任意字符序列[\s\S] 一次到无限次,尽可能少,根据需要扩展(惰性)
    • (?=\n#\S+ ) - 前瞻肯定断言,确保所需的匹配序列后跟\n#\S+(以# 和非空白字符序列\S+ 开头的单独行)

    【讨论】:

    • 完美!非常感谢您的解决方案和解释。
    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    相关资源
    最近更新 更多