簡體   English   中英

re.sub在python中:詳細模式不適用於替換模式嗎?

[英]re.sub in python : verbose mode does not work with replacement pattern?

有什么辦法可以解決re.sub的限制嗎? 對於替換模式中的詳細模式(此處帶有反向引用),它不能完全發揮作用; 它不能消除空格或注釋(但它確實可以正確解釋反向引用)。

import remport re

ft1=r"""(?P<test>[0-9]+)"""
ft2=r"""\g<test>and then: \g<test> #this remains"""

print re.sub(ft1,ft2,"front 1234 back",flags=re.VERBOSE) #Does not work 
#result: front 1234and then: 1234 #this remains back

re.VERBOSE不適用於替換模式...是否有解決方法? (比重新匹配后使用組更簡單。)

這是我發現“編譯” sub的替換表達式的唯一方法。 還有一些額外的約束:空格和換行符都必須像為re match表達式寫空格一樣寫在方括號([]和[\\ n \\ n \\ n]中),並且整個replace表達式應具有冗長的含義。換行符開頭。

例如:這將搜索一個字符串並檢測在/ ins /和/ del /之后重復的單詞,然后將這些出現替換為之前出現的單個單詞。

匹配和替換表達式都很復雜,這就是為什么我想要替換表達式的詳細版本。

===========================

import re

test = "<p>Le petit <ins>homme à</ins> <del>homme en</del> ressorts</p>"


find=r"""
    <ins>
    (?P<front>[^<]+)          #there is something added that matches 
    (?P<delim1>[ .!,;:]+)     #get delimiter
    (?P<back1>[^<]*?)
    </ins>
    [ ]
    <del>
    (?P=front)
    (?P<delim2>[ .!,;:]+)
    (?P<back2>[^<]*?)
    </del>
"""
replace = r"""
    <<<<<\g<front>>>>>         #Pop out in front matching thing
    <ins>
    \g<delim1>
    \g<back1>
    </ins>
    [ ]     
    <del>    
    \g<delim2>             #put delimiters and backend back
    \g<back2>
    </del>
"""

flatReplace = r"""<<<<<\g<front>>>>><ins>\g<delim1>\g<back1></ins> <del>\g<delim2>\g<back2></del>"""


def compileRepl(inString):

    outString=inString
    #get space at front of line
    outString=re.sub(r"\n\s+","\n",outString)
    #get space at end of line
    outString=re.sub(r"\s+\n","",outString) 
    #get rid of comments
    outString=re.sub(r"\s*#[^\n]*\n","\n",outString)
    #preserve space in brackets, and eliminate brackets
    outString=re.sub(r"(?<!\[)\[(\s+)\](?!\[)",r"\1",outString)
    # get rid of newlines not in brackets
    outString=re.sub(r"(?<!\[)(\n)+(?!\])","",outString)
    #get rid of brackets around newlines
    outString=re.sub(r"\[((\\n)+)\]",r"\1",outString)
    #trim brackets    
    outString=re.sub(r"\[\[(.*?)\]\]","[\\1]",outString)
    return outString


assert(flatReplace == compileRepl(replace))


print test
print compileRepl(replace)
print re.sub(find,compileRepl(replace),test, flags=re.VERBOSE)

#<p>Le petit <ins>homme à</ins> <del>homme en</del> ressorts</p>
#<<<<<\g<front>>>>><ins>\g<delim1>\g<back1></ins> <del>\g<delim2>\g<back2></del>
#<p>Le petit <<<<<homme>>>><ins> à</ins> <del> en</del> ressorts</p>

您可以首先使用re.compile編譯正則表達式。 在這里,您可以使用re.VERBOSE標志。 以后,您可以將這些編譯后的表達式作為參數傳遞給re.sub()

暫無
暫無

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

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