Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python RE:使用组的替换_Python_Regex - Fatal编程技术网

Python RE:使用组的替换

Python RE:使用组的替换,python,regex,Python,Regex,我已经提供了下面的代码和输出。我无法理解这种替代是如何发生的。如果你能一步一步地解释,那将很有帮助 import re text = 'section{First} section{second}' p = re.compile('section{([^}]*)}') print 'before substitution: ', text print 'after substitution: ', p.sub(r'subsection{\1}', text) 输出 模式节{([^}]*)}匹配

我已经提供了下面的代码和输出。我无法理解这种替代是如何发生的。如果你能一步一步地解释,那将很有帮助

import re
text = 'section{First} section{second}'
p = re.compile('section{([^}]*)}')
print 'before substitution: ', text
print 'after substitution: ', p.sub(r'subsection{\1}', text)
输出
模式
节{([^}]*)}
匹配
节{First}
。特别是,括号表示捕获组:
[^}]*
首先匹配
,该字符串被捕获,以便以后使用。具体地说,它可以在替换中称为
\1
。在字符串格式术语中,
节{First}
被替换为
'subsection{%s}''%First'
,即
subsection{First}
。第二个的部分是相同的。

基本上对于正则表达式,括号组指的是组,您可以调用这些组来获取该组的字符串表示形式。
before substitution:  section{First} section{second}
after substitution:  subsection{First} subsection{second}