Home > Software design >  Python3 Replace String Using Dict with Regex
Python3 Replace String Using Dict with Regex

Time:09-29

I have an input field which a user can insert variables that are enclosed within a *, I am then using regex to grab the variables and I'm trying to look them up in the dict and then replace them in the input string. In the below code I have managed to write the regex that gets the variables and then matches it and creates a list with the values but I am unsure on how to use it to replace what's in the string.

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'

I got close by using the below code that found on here, however, it doesn't match when the variables in the input field have no space.

#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)

CodePudding user response:

You can use

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

See the Python demo

You do not need to capture the whole matches, that is why ( and ) are removed now from the pattern.

The \*[^*]*\* pattern matches a *, then zero or more chars other than * and then a *.

The whole match is passed to re.sub replacement argument via a lambda expression and the variables.get(x.group(), x.group()) fetches the corresponding value from the variables dictionary, or puts the match back if there is no item with the match value as key.

  • Related