String replacement with Python regular expression

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/

program

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

String replacement with Python regular expression
Regular expression manipulation with Python
Make one repeating string with a Python regular expression.
Determine if a string is a time with a python regular expression
Regular expression with pymongo
python regular expression memo
Regular expression in Python
Regular expression in Python
Python 處 處 regular expression Notes
String format with Python% operator
Change the string to be replaced according to the matched string by replacing with Python regular expression
Decompose hostname with co.jp with regular expression
Python string
Handling regular expressions with PHP / Python
Get the matched string with a regular expression and reuse it when replacing on Python3
Start / end match in python regular expression
(Python) HTML reading and regular expression notes
Replace non-ASCII with regular expressions in Python
Python: Simplified morphological analysis with regular expressions
[Python] A function that searches the entire string with a regular expression and retrieves all matching strings.
Python: String concatenation
FizzBuzz with Python3
Scraping with Python
python string slice
Statistics with python
Scraping with Python
Regular expression Greedy
Get the number of searches with a regular expression. SeleniumBasic VBA Python
Python with Go
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
[Python] Regular Expressions Regular Expressions
with syntax (Python)
URL match checking and extraction with python regular expression Regex Full version
Bingo with python
Solve with Ruby, Perl, Java and Python AtCoder ABC 047 C Regular Expression
Zundokokiyoshi with python
Python2 string type
Python string format
Python # string type
Python string inversion
Regular expression re
Excel with Python
Microcomputer with Python
Cast with python
[Python] Get rid of dating with regular expressions
Regular expression symbolic group name in Python / Ruby
Decrypt a string encrypted on iOS with Python
[Python] Expression (1,2) does not make tuples with parentheses
Serial communication with Python
Zip, unzip with python
Django 1.11 started with Python3.6
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)