我無法替換包含特殊字符的字串中的字母字符。
import re
s = 'F6[ab]\nF3[ab]'
n = 'F6[ab]' # <= want to keep this in my string but want to change 'ab' in the new line
k = 'ab' # <= do not want to keep this in my string
c = '1' # <= change 'ab' -> '1'
re.sub(f'(?!{n}){k}', c, s)
# => 'F6[ab]\nF3[1'
# but I want this output
# => 'F6[ab]\nF3[1]'
uj5u.com熱心網友回復:
您可以在正則運算式中使用分組來捕獲和保留您想要保留在最終結果中的內容。re.sub像這樣在 lambda 中使用它:
import re
s = 'F6[ab]\nF3[ab]'
n = 'F6[ab]' # <= want to keep this in my string but want to change 'ab' in the new line
k = 'ab' # <= do not want to keep this in my string
c = '1' # <= change 'ab' -> '1'
repl = re.sub(r'(' re.escape(n) rf')|\b{k}\b',
lambda m: m.group(1) if m.group(1) else c, s)
輸出:
'F6[ab]\nF3[1]'
它使以下正則運算式:
(F6\[ab\])|\bab\b
Code Demo
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408169.html
標籤:
