Posted in Python onAugust 19, 2017
本文实例讲述了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. 替换字符中含参数 \g<1>
>>> bds = '10+6/5-4*2' # 表达式 >>> m = re.sub(r'([*+-/])', ' \g<1> ', bds) >>> m '10 + 6 / 5 - 4 * 2'
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?"
Python正则捕获操作示例
- Author -
罗兵声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@