【发布时间】:2013-08-10 00:46:33
【问题描述】:
我有一个表单的正则表达式
def parse(self, format_string):
for m in re.finditer(
r"""(?: \$ \( ( [^)]+ ) \) ) # the field access specifier
| (
(?:
\n | . (?= \$ \( ) # any one single character before the '$('
)
| (?:
\n | . (?! \$ \( ) # any one single character, except the one before the '$('
)*
)""",
format_string,
re.VERBOSE):
...
我想用一些自定义的速记“常量”替换所有重复序列 (\$ \(),如下所示:
def parse(self, format_string):
re.<something>('\BEGIN = \$\(')
for m in re.finditer(
r"""(?: \BEGIN ( [^)]+ ) \) ) # the field access specifier
| (
(?:
\n | . (?= \BEGIN ) # any one single character before the '$('
)
| (?:
\n | . (?! \BEGIN ) # any one single character, except the one before the '$('
)*
)""",
format_string,
re.VERBOSE):
...
有没有办法用正则表达式本身来做到这一点(即不使用 Python 的字符串格式将 \BEGIN 替换为 \$\()?
澄清:Python 源代码仅用于上下文和说明。我正在寻找 RE 解决方案,它可以在某些 RE 方言中使用(可能不是 Python 的方言),而不是专门针对 Python 的解决方案。
【问题讨论】:
-
不,抱歉。字符串格式有什么问题?
-
嗯,不是“可移植的”,因为生成的带有自定义简写的正则表达式可以用于不同的编程语言。
-
许多正则表达式方言不支持冗长的正则表达式。或断言。
-
在 PCRE 中是可能的,但我猜您正在寻找 Python 解决方案?
-
@HamZa 我认为这只是 OP 想象的重用语法可能是什么样子的一个例子。
标签: regex