代码之家  ›  专栏  ›  技术社区  ›  David J.

Python3.6正则表达式产生意外结果(尽管使用字符串文本)

  •  1
  • David J.  · 技术社区  · 6 年前

    不久前我 an almost identical problem to this one and it was fixed by using string literals instead of literal strings 是的。这一次,我注意使用字符串文字,但没有解决问题。

    我试图从字符串中提取一个部分,从python得到的结果与regex101显示的结果不同。我在用这个

    Supersedes:?[\\r\\n ]+(?:[A-Za-z\-0-9])*[\\w\-\\s]+[\\r\n ]+(.*)[\\r\\n ]+Serial Numbers:?
    

    要匹配此文本:

    \ r\n\r\n没有更改为VGA-77气体模块 程序集(0110444290)服务序列号 编号:\ r\nus00000000-us9999999\r\n\r

    我期待着第一批被抓获的人给我

    n\r\nChanges to VGA-77 gas module assembly (0110444290)\r\n\r\nService
    

    https://regex101.com/r/eHdhBV/2

    但当我在python中尝试时:

    rx = r'Supersedes:?[\r\n ]+(?:[A-Za-z\-0-9])*[\w\-\s]+[\r\n ]+(.*)[\r\n ]+Serial Numbers:?'
    string = '\r\n\r\nSupersedes\r\nNone\r\n\r\nChanges to VGA-77 gas module assembly (0110444290)\r\n\r\nService Serial Numbers:\r\nUS00000000-US99999999\r\n\r'
    result = re.search(rx, string, re.M|re.S)
    result[1]
    '(0110444290)\r\n\r\nService'
    

    结果与regex101上显示的不同。这是什么原因?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Wiktor Stribiżew    6 年前

    要解决当前问题,可以使用

    m = re.search(r'Supersedes:?\s*[^\r\n]*[\r\n]+(.*?)[ \r\n]+Serial Numbers', s, re.S)
    if m:
        print(m.group())
    

    regex demo online 是的。

    请注意,您应该使用 串常量 在在线regex测试中,也就是说,转换 \n \r 换行。

    图案细节

    • Supersedes:? - Supersedes: Supersedes
    • \s* -任何0+空格
    • [^\r\n]* -除lf和cr之外的任何0+字符
    • [\r\n]+ -1+LR或CR符号
    • (.*?) -组1:任何0+字符,尽可能少
    • [ \r\n]+ -1+空格,CR或LF
    • Serial Numbers -字面的 序列号 弦。