[英]python regex substitute group with variable
在python中,需要用變量替換Regex字符串中找到的組。 但僅替換組,而不替換整個正則表達式結果。
這是我到目前為止所擁有的:
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)
我從搜索“ regex”中得到的結果是:
name */
'test_name_to_replace.stp
第一組在哪里
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
文檔始終是您的朋友,因為這在正則表達式語法中有非常清楚的記錄:
\\number
匹配相同編號組的內容。
但是您這里不需要匹配的組,請嘗試使用:
接着:
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.