簡體   English   中英

具有特定結尾的多行圖案

[英]Multiline pattern with specific ending

我試圖匹配一些多行模式,該模式具有最后一行的特定序列結尾。

我正在使用re.DOTALL | re.MULTILINE可以匹配多行,但是不能捕獲我想要的第一行的末尾。

title = re.compile(
    r"TITLE\([^\"\);]*",
    re.DOTALL | re.MULTILINE
)

titles = re.findall(patterns.title, file)

字符串形式:

TITLE("blah
    blah_blah
    contain_"
    contain_)
    contain_;
    but_not_");
");

結果是Title(" ,但是我想要所有字符串。

解決此問題的一種方法是使用超前測試來測試“結束令牌”(在您的情況下為");

re.compile(r"TITLE\(\"((?:(?!\"\);).)*)", re.DOTALL | re.IGNORECASE)

將匹配示例字符串的這一部分

blah_blah
contain_"
contain_)
contain_;
but_not_

說明:

TITLE            # literal: TITLE (case-insensitive with re.IGNORECASE)
\(\"             # literal: ("
(                # group 1
  (?:            #   non-capturing group
    (?!          #     negative look-ahead
      \"\);      #       not followed by: ");
    )            #     end look-ahead
    .            #     match next character (including \n with re.DOTALL)
  )*             #   end non-capturing group, repeat
)                # end group 1 (will contain the final match)

https://regex101.com/r/km3uuV/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM