[英]Regex to capture named groups in any order
我有一種情況,我需要使用對Python的re.sub()的單個調用來查找和替換字符串中的項目。 如果聽起來像是人為限制,那就考慮一下這是一項腦力鍛煉,但要知道這是我必須處理的現實生活中的限制。
我要匹配並替換以下任一行:
foo -some-arg -o %output %input
foo %input -other-random-arg=baz -o %output
有了這個:
bar %output %input.out
文件名%input和%output可以是與[a-zA-Z0-9._-]+
匹配的任何名稱,但始終以%
[a-zA-Z0-9._-]+
我想出了這種替代方法,但效果不佳。
r'''(?x) # Begin verbose regex
foo[ ] # foo and a space
(?=.*?-o[ ] # Lookahead for the first occurrence of -o
(?P<a>%\S+\b) # Output filename -> Group 'a'
)
(?=.*? # Lookahead from the same place as the first lookahead
# so the two filenames can match in any order.
(?!-o[ ]%\S+\b) # Do not match the output file
(?P<b>%\S+\b) # Any filename -> Group 'b'
).* # Match anything ''',
r'bar \g<b> \g<a>.out' # Replacement
我經常以兩個重復的文件名之一結束,例如:
bar %output %output.out
有沒有辦法以它們出現的順序命名捕獲兩個文件名? 看來,如果我可以在匹配其中一個先行時提高正則表達式引擎的指針,就可以完成這項工作。
由於所有參數均以破折號開頭,並且輸入和輸出始終僅出現一次,因此您可以使用這種忽略順序的模式:
foo(?: -o (?P<output>\S+)| -\S+| (?P<input>\S+))+
和替換
bar \1 \2.out
注意:如果要處理包含空格(在命令行中轉義的空格)的文件名,則需要將\\S+
更改為(?:[^\\s\\\\]+(?:\\\\.[^\\s\\\\]*)*|[^\\s\\\\]*(?:\\\\.[^\\s\\\\]*)+)
(僅適用於輸入和輸出)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.