You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写无需硬编码原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 with 0x (use this if you want to avoid replacing other potential matches).
  • \1 in the replacement string references the content from the first capturing group, and we append your new ModuleId converted to a hex string (use hex() if your Module_Id is an integer; if it's already a string like "0x87400271", just remove the hex() call).

This way, your regex will work regardless of what the original ModuleId value was—no more hardcoding!

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:49:08