簡體   English   中英

Python3 使用帶有正則表達式的字典替換字符串

[英]Python3 Replace String Using Dict with Regex

我有一個輸入字段,用戶可以在其中插入包含在 * 中的變量,然后我使用正則表達式來獲取變量,我試圖在字典中查找它們,然后在輸入字符串中替換它們。 在下面的代碼中,我設法編寫了獲取變量的正則表達式,然后匹配它並創建一個包含值的列表,但我不確定如何使用它來替換字符串中的內容。

variables = {
    '*FFullName*': 'Raz Smith',
    '*FFirstName*': 'Raz',
    '*FSurname*': 'Smith',
    '*Subject*': 'hello',
    '*Day*': '27',
}

input = '*Day* *Subject* to *FFirstName* *FSurname*'

#get all the *variables* and add to list
var_input = re.findall('(\*.*?\*)', input)

#match above list with dict
match = list(map(variables.__getitem__, var_input))

#how to replace these in input?

#expected outcome: input = '27 Hello to Raz Smith'

我通過使用此處找到的以下代碼接近,但是,當輸入字段中的變量沒有空格時,它不匹配。

#example of input not working correctly

input = '*Day**Subject*to*FFirstName**FSurname*'

pattern = re.compile(r'(?<!\*)(' + '|'.join(re.escape(key) for key in variables.keys()) + r')(?!\*)')
result = pattern.sub(lambda x: variables[x.group()], input)

您可以使用

import re
 
variables = {
    '*FFullName*': 'Raz Smith',
    '*FFirstName*': 'Raz',
    '*FSurname*': 'Smith',
    '*Subject*': 'hello',
    '*Day*': '27',
}
 
text = '*Day* *Subject* to *FFirstName* *FSurname*'
var_input = re.sub(r'\*[^*]*\*', lambda x: variables.get(x.group(), x.group()), text)
print(var_input)
# => 27 hello to Raz Smith

請參閱Python 演示

您不需要捕獲整個匹配項,這就是現在從模式中刪除()的原因。

\*[^*]*\*模式匹配* ,然后匹配除*以外的零個或多個字符,然后匹配*

整個匹配通過 lambda 表達式傳遞給re.sub替換參數,並且variables.get(x.group(), x.group())variables字典中獲取相應的值,或者如果有則放回匹配沒有以匹配值作為鍵的項目。

暫無
暫無

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

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