在Python中使用正则表达式匹配的字符串周围添加括号
16lz
2021-01-22
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". The newly generated string should be "Alan Turing (1912-1954)".
例如:我的原始字符串s是“Alan Turing 1912-1954”,我的正则表达式恰好匹配“1912-1954”。新生成的字符串应为“Alan Turing(1912-1954)”。
1 个解决方案
#1
9
Solution 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:
>>> 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)'
更多相关文章
- 用python将二进制整数或字符串写入文件
- python1.返回一个字符串中出现次数第二多的单词 2.字符串中可能
- Python笔记(九):字符串操作
- python 产生随机数,随机字符串
- linux shell脚本编程笔记(四): 获取字符串长度的七种方法
- Linux Shell编程(15)——操作字符串
- linux中常用时间和字符串之间相互转化
- 文本文件到字符串数组?
- 字符串处理函数strcat和strtok