简体   繁体   English

在Python中使用正则表达式匹配的字符串周围添加括号

[英]Adding parentheses around a string matched by a regex in Python

Given a regex and a string s, I would like to generate a new string in which any substring of s matched by the regex is surrounded by parentheses. 给定正则表达式和字符串s,我想生成一个新的字符串,其中正则表达式匹配的s的任何子字符串都被括号括起来。

For example: My original string s is "Alan Turing 1912-1954" and my regex happens to match "1912-1954". 例如:我的原始字符串s是“Alan Turing 1912-1954”,我的正则表达式恰好匹配“1912-1954”。 The newly generated string should be "Alan Turing (1912-1954)". 新生成的字符串应为“Alan Turing(1912-1954)”。

Solution 1: 解决方案1:

>>> re.sub(r"\d{4}-\d{4}", r"(\g<0>)", "Alan Turing 1912-1954")
'Alan Turing (1912-1954)'

\\g<0> is a backreference to the entire match ( \\0 doesn't work; it would be interpreted as \\x00 ). \\g<0>是对整个匹配的反向引用( \\0不起作用;它将被解释为\\x00 )。

Solution 2: 解决方案2:

>>> regex = re.compile(r"\d{4}-\d{4}")
>>> regex.sub(lambda m: '({0})'.format(m.group(0)), "Alan Turing 1912-1954")
'Alan Turing (1912-1954)'

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

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