Home  >  Article  >  Backend Development  >  Examples of regular capture operations in Python

Examples of regular capture operations in Python

黄舟
黄舟Original
2017-08-20 10:48:151274browse

这篇文章主要介绍了Python正则捕获操作,结合具体实例形式分析了Python基于正则表达式的分组、捕获、替换等相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python正则捕获操作。分享给大家供大家参考,具体如下:

目的: 给表达式 '10+6/5-4*2' 中每个运算符左右都加一个空格字符,变成:'10 + 6 / 5 - 4 * 2'

思路: 分组、捕获、替换

1. 替换字符中含参数 \1 (此处不能叫参数,想不到叫什么,那就不管它~~)


>>> bds = '10+6/5-4*2' # 表达式
>>> m = re.sub(r'([*+-/])', ' \1 ', bds) # 注意\1左右皆有一个空格!!
>>> m
 '10 + 6 / 5 - 4 * 2'

2. 替换字符中含参数 \gf35d6e602fd7d0f0edfa6f7d103c1b57


>>> bds = '10+6/5-4*2' # 表达式
>>> m = re.sub(r&#39;([*+-/])&#39;, &#39; \g<1> &#39;, bds)
>>> m
 &#39;10 + 6 / 5 - 4 * 2&#39;

3. 模式中也可含参数 \1


>>> greed = "Hello Jack! Are you OK, Jack?"
>>> m = re.sub(r"Hello (\w+)! Are you OK, \1?", "\g<1>", greed)
>>> m
"Hello Jack! Are you OK, Jack?"

4. 模式中也可含参数 :命名组 (?P=yourname)


>>> greed = "Hello Jack! Are you OK, Jack?"
>>> m = re.sub(r"Hello (?P<yourname>\w+)! Are you OK, (?P=yourname)?", "\g<yourname>", greed)
>>> m
"Hello Jack! Are you OK, Jack?"

The above is the detailed content of Examples of regular capture operations in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn