【问题标题】:python regex substitute group with variable带有变量的python正则表达式替换组
【发布时间】: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


【解决方案1】:

文档永远是你的朋友,因为这在Regular Expression Syntax 中有非常清楚的记录:

  • \number

    匹配同号组的内容。

但您不需要在这里匹配组,请尝试使用:

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

然后:

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 */ (''),

【讨论】:

  • 如果文件名有数字和其他字符怎么办? /w 将不起作用
  • \w 将匹配 [a-zA-Z0-9_] 因此,如果您有其他字符,只需使用该显式列表并根据需要添加
  • 实际上更好,而不是 \w 我可以使用:[^']+.stp 并且我不再需要担心这些组了。它只是超级慢!!!!!!
  • 这可能允许文件名中包含无效字符,但如果这不是问题,那就去吧。
猜你喜欢
  • 2022-07-08
  • 1970-01-01
  • 2023-03-17
  • 2012-08-26
  • 2021-08-19
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多