Replace using the sub function of the re module.
How to use the re module Reference https://note.nkmk.me/python-re-match-search-findall-etc/
The behavior of the program is as follows.
The values of response1, response3, and response4 are converted as follows. 1) If target_str and tmp_json are: target_str = "asdasdasd ${key1} asdasdasdasd %key2% asdasdasd |key1| asdasdasd" tmp_json = {"key1" : "value1","key2" : "value2"} The value after replacement is rewritten with the value corresponding to the key of tmp_json as follows. asdasdasd value1 asdasdasdasd value2 asdasdasd value1 asdasdasd
If target_str and tmp_json are: target_str = "asdasdasd ${k1} asdasdasdasd %k2% asdasdasd |key1| asdasdasd" tmp_json = {"key1" : "value1","key2" : "value2"} The replaced value can be rewritten with the tmp_json key itself as shown below. asdasdasd k1 asdasdasdasd k2 asdasdasd value1 asdasdasd
If target_str and tmp_json are: target_str = "asdasdasd $key1} asdasdasdasd key2% asdasdasd key1| asdasdasd" tmp_json = {"key1" : "value1","key2" : "value2"} It doesn't match the regular expression pattern, so it's the same as the original value.
The value of response2 is rewritten with the value that matches the regular expression regardless of the value of tmp_json. If it does not match, it will be the same as the original value as in 3.
#-*- encoding:utf-8 -*-
from functools import partial
import re
def call_back(match: re.match,tmp_dict=None) -> str:
"""
call back
Args:
match: match object of re module
tmp_dict: something dict object
Returns:
value
"""
value = match.group("param")
if tmp_dict != None and value in tmp_dict:
return tmp_dict[value]
return value
def search_and_convert(expression: str, tmp_json: dict) -> str:
"""
Search specified string value, and replace it to the specified one
Args:
expression: would be converted string
tmp_json: something dict value
Returns:
expression
"""
l = [
{
"reg" : re.finditer(r"(?<=\$\{)\w+(?=\})",expression),
"prefix" : "${",
"suffix" : "}"
},
{
"reg" : re.finditer(r"(?<=%)\w+(?=%)",expression),
"prefix" : "%",
"suffix" : "%"
},
{
"reg" : re.finditer(r"(?<=\|)\w+(?=\|)",expression),
"prefix" : "|",
"suffix" : "|"
}
]
for item in l:
match_iterator = item["reg"]
if match_iterator:
for match in match_iterator:
value = match.group()
converted_value = value
if value in tmp_json:
converted_value = tmp_json[value]
expression = expression.replace(
item["prefix"] + value + item["suffix"],
converted_value
)
return expression
if __name__ == "__main__":
target_str = "asdasdasd ${key1} asdasdasdasd %key2% asdasdasd |key1| asdasdasd"
tmp_json = {"key1" : "value1","key2" : "value2"}
#re.sub with lambda
print(f"target_str = {target_str}")
response1 = re.sub(r"\$\{(?P<param>\w+)\}",lambda x: tmp_json[x.group("param")] if x.group("param") in tmp_json else x.group("param"),target_str)
response1 = re.sub(r"%(?P<param>\w+)%",lambda x: tmp_json[x.group("param")] if x.group("param") in tmp_json else x.group("param"),response1)
response1 = re.sub(r"\|(?P<param>\w+)\|",lambda x: tmp_json[x.group("param")] if x.group("param") in tmp_json else x.group("param"),response1)
print(f"response1 = {response1}")
#re.sub with call back.
print(f"\033[33mtarget_str = {target_str}")
response2 = re.sub(r"\$\{(?P<param>\w+)\}",call_back,target_str)
response2 = re.sub(r"%(?P<param>\w+)%",call_back,response2)
response2 = re.sub(r"\|(?P<param>\w+)\|",call_back,response2)
print(f"response2 = {response2}\033[0m")
#re.sub with call back which has a fixed augument.
print(f"target_str = {target_str}")
response3 = re.sub(r"\$\{(?P<param>\w+)\}",partial(call_back,tmp_dict=tmp_json),target_str)
response3 = re.sub(r"%(?P<param>\w+)%",partial(call_back,tmp_dict=tmp_json),response3)
response3 = re.sub(r"\|(?P<param>\w+)\|",partial(call_back,tmp_dict=tmp_json),response3)
print(f"response3 = {response3}")
#re.search & replace
print(f"\033[33mtarget_str = {target_str}")
response4 = search_and_convert(target_str,tmp_json)
print(f"response4 = {response4}\033[0m")
if response1 == response3 == response4:
print("OK")
else:
raise Exception("Failed")
Recommended Posts