简体   繁体   English

带有变量的python正则表达式替代组

[英]python regex substitute group with variable

in python, need to substitute a group found in Regex string with a variable. 在python中,需要用变量替换Regex字符串中找到的组。 but just substitute the group, not the entire regex result. 但仅替换组,而不替换整个正则表达式结果。

here is what I have so far: 这是我到目前为止所拥有的:

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)

the result I from the search "regex" is: 我从搜索“ regex”中得到的结果是:

name */ 
'test_name_to_replace.stp

where group 1 is 第一组在哪里

name */ 
'

and group 0 is 而组0是

test_name_to_replace.stp

I need to keep group 1 and replace group 0 but the subs string isn't working the special character $1 before the variable, I get a result like this: 我需要保留组1并替换组0,但是subs字符串在变量之前的特殊字符$ 1上不起作用,我得到如下结果:

New_Content = "FILE_NAME(
           $1New_Name.stp',
           /* time_stamp */ '2018-05-28T14:34:32+02:00',
           /* author */ (''),
           /* organization */ (''),"

it deletes the group1 它删除了group1

The documentation is always your friend, as this is very clearly documented in Regular Expression Syntax : 文档始终是您的朋友,因为这在正则表达式语法中有非常清楚的记录:

  • \\number

    Matches the contents of the group of the same number. 匹配相同编号组的内容。

But you don't need matching groups here, try using: 但是您这里不需要匹配的组,请尝试使用:

\\'(\\w+\\.stp)\\'

And then: 接着:

subst = "'{}'".format(replaceVariable)
re.sub(r"\'(\w+\.stp)\'", subst, content, 0, re.MULTILINE)

# Result
FILE_NAME(
           /* name */ 
           'New_Name.stp',
           /* time_stamp */ '2018-05-28T14:34:32+02:00',
           /* author */ (''),
           /* organization */ (''),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM