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}