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

Examples of regular capture operations in Python

黄舟
Release: 2017-08-20 10:48:15
Original
1324 people have browsed it

这篇文章主要介绍了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'
Copy after login

2. 替换字符中含参数 \g<1>


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

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?"
Copy after login

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?"
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template