[Solved] Using Python regex matches in eval()


You don’t need eval. In fact, you want to avoid eval like the plague.

You can achieve the same output with match.expand:

mystr="abc123def456ghi"
user_input1 = r'(\d+).+?(\d+)'
user_input2 = r'\2\1'
match = re.search(user_input1, mystr)
result = match.expand(user_input2)
# result: 456123

The example about inserting 999 between the matches is easily solved by using the \g<group_number> syntax:

mystr="abc123def456ghi"
user_input1 = r'(.+?)(\d+).+?(\d+)(.+)'
user_input2 = r'\g<3>999\2'
match = re.search(user_input1, mystr)
result = match.expand(user_input2)
# result: 456999123

As you can see, if all you need to do is move captured text around and insert new text, the regex module has you covered. Only use eval if you really have to execute code.

6

solved Using Python regex matches in eval()