如何编写无需硬编码原ID的Python正则表达式以替换字符串中的ModuleId值
Solution for Dynamic ModuleId Replacement in Python
Got it, let's fix that regex so you don't have to hardcode the old ModuleId value anymore. The key is to match the fixed prefix pattern (--ModuleId ) plus the variable ID part (instead of the specific old ID), then replace just the ID part with your new value.
Here's the improved code:
import re # Your original string My_String = '_test --fid --ModuleId 0x51900879 -- p' # Your target ModuleId (can be an integer or string) Module_Id = 0x87400271 # Option 1: General-purpose match (works for any non-whitespace ID) updated_string = re.sub(r'(--ModuleId )\S+', r'\1{}'.format(hex(Module_Id)), My_String) # Option 2: Precise hex ID match (safer, avoids accidental replacements) updated_string = re.sub(r'(--ModuleId )0x[0-9A-Fa-f]+', r'\1{}'.format(hex(Module_Id)), My_String) print(updated_string) # Output: _test --fid --ModuleId 0x87400271 -- p
Breakdown of the regex:
(--ModuleId ): This is a capturing group that grabs the fixed prefix (--ModuleId) so we can reuse it in the replacement. No need to retype it!\S+: Matches any sequence of non-whitespace characters (covers any ID format here).0x[0-9A-Fa-f]+: A more precise pattern that only matches hexadecimal IDs starting with0x(use this if you want to avoid replacing other potential matches).\1in the replacement string references the content from the first capturing group, and we append your new ModuleId converted to a hex string (usehex()if your Module_Id is an integer; if it's already a string like"0x87400271", just remove thehex()call).
This way, your regex will work regardless of what the original ModuleId value was—no more hardcoding!
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

