Home > database >  Python Regex Substitution
Python Regex Substitution

Time:10-09

I need a regular expression to replace My_String with the new ModuleId:

My_String = '_test --fid --ModuleId 0x51900879 -- p'
Module_Id = 0x87400271

So the final outcome should be following:

Result-String = '_test --fid --ModuleId 0x87400271 -- p'

I need a regex like following but without hardcoding the id 0x51900879

My_String = re.sub("ModuleId 0x51900879", "ModuleId M_id", My_String)

CodePudding user response:

Here is a example using re.sub and int conversion to hex string:

import re

My_String = '_test --fid --ModuleId 0x51900879 -- p'
Module_Id = 0x87400271
re.sub('0x\d{8}', '0x%0.2X' % Module_Id, My_String)

output: '_test --fid --ModuleId 0x87400271 -- p'

  • Related