我正在嘗試創建一個簡單的降價乳膠轉換器,只是為了學習
python和基本的正則表達式,但我不知道試圖弄清楚為什么下面的代碼不起作用:
re.sub (r'\[\*\](.*?)\[\*\]: ?(.*?)$', r'\\footnote{\2}\1', s, flags=re.MULTILINE|re.DOTALL)
我想轉換像:
s = """This is a note[*] and this is another[*]
[*]: some text
[*]: other text"""
至:
This is a note\footnote{some text} and this is another\footnote{other text}
這就是我得到的(使用上面的正則表達式):
This is a note\footnote{some text} and this is another[*]
[*]: note 2
為什么模式只匹配一次?
編輯:
我嘗試了以下先行斷言:
re.sub(r'\[\*\](?!:)(?=.+?\[\*\]: ?(.+?)$',r'\\footnote{\1}',flags=re.DOTALL|re.MULTILINE)
#(?!:) is to prevent [*]: to be matched
現在它匹配所有腳注,但它們沒有正確匹配.
s = """This is a note[*] and this is another[*]
[*]: some text
[*]: other text"""
給了我
This is a note\footnote{some text} and this is another\footnote{some text}
[*]: note 1
[*]: note 2
有什么想法嗎?