本文实例讲述了Python正则捕获操作。分享给大家供大家参考,具体如下:
目的: 给表达式 '10+6/5-4*2' 中每个运算符左右都加一个空格字符,变成:'10 + 6 / 5 - 4 * 2'
思路: 分组、捕获、替换
1. 替换字符中含参数 \1 (此处不能叫参数,想不到叫什么,那就不管它~~)
1
2
3
4
|
>>> bds = '10+6/5-4*2' # 表达式
>>> m = re.sub(r '([*+-/])' , ' \1 ' , bds) # 注意\1左右皆有一个空格!!
>>> m
'10 + 6 / 5 - 4 * 2'
|
2. 替换字符中含参数 \g<1>
1
2
3
4
|
>>> bds = '10+6/5-4*2' # 表达式
>>> m = re.sub(r '([*+-/])' , ' \g<1> ' , bds)
>>> m
'10 + 6 / 5 - 4 * 2'
|
3. 模式中也可含参数 \1
1
2
3
4
|
>>> 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)
1
2
3
4
|
>>> 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?"
|
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://www.cnblogs.com/hhh5460/p/5167004.html