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)'

更多相关文章

  1. 用python将二进制整数或字符串写入文件
  2. python1.返回一个字符串中出现次数第二多的单词 2.字符串中可能
  3. Python笔记(九):字符串操作
  4. python 产生随机数,随机字符串
  5. linux shell脚本编程笔记(四): 获取字符串长度的七种方法
  6. Linux Shell编程(15)——操作字符串
  7. linux中常用时间和字符串之间相互转化
  8. 文本文件到字符串数组?
  9. 字符串处理函数strcat和strtok

随机推荐

  1. Android Application - Painting
  2. Android Studio放大缩小字体
  3. some step in studying android
  4. Android(安卓)小应用之一个activity实现
  5. Android(安卓)apk的维护与升级
  6. 在 Android(安卓)上使用 XML 和 JSON,第 2
  7. android解析json数组
  8. android 开发中遇到错误及解决办法总结(
  9. Android使用WCF的服务程序之入门
  10. Android Studio插件