【发布时间】:2018-11-09 14:36:14
【问题描述】:
在python中,需要用一个变量替换在正则表达式字符串中找到的组。但只是替换组,而不是整个正则表达式结果。
这是我目前所拥有的:
content = "FILE_NAME(
/* name */
'test_name_to_replace.stp',
/* time_stamp */ '2018-05-28T14:34:32+02:00',
/* author */ (''),
/* organization */ (''),"
replaceVariable = "New_Name.stp"
regex = r"(name.*\n*').*.stp"
subst = r"$1%s" % re.escape(replaceVariable)
New_Content = re.sub(regex, subst, content, 0, re.MULTILINE)
搜索“正则表达式”的结果是:
name */
'test_name_to_replace.stp
第 1 组在哪里
name */
'
第 0 组是
test_name_to_replace.stp
我需要保留第 1 组并替换第 0 组 但是 subs 字符串在变量之前的特殊字符 $1 不起作用,我得到这样的结果:
New_Content = "FILE_NAME(
$1New_Name.stp',
/* time_stamp */ '2018-05-28T14:34:32+02:00',
/* author */ (''),
/* organization */ (''),"
它会删除 group1
【问题讨论】:
-
使用
\1引用python 中的组。不是$1
标签: python regex regex-group