本文实例讲述了Python正则捕获操作。分享给大家供大家参考,具体如下:
[b]目的:[/b] 给表达式 '10+6/5-4*2' 中每个运算符左右都加一个空格字符,变成:'10 + 6 / 5 - 4 * 2'
[b]思路:[/b] 分组、捕获、替换
[b]1. 替换字符中含参数[/b]
\1 (此处不能叫参数,想不到叫什么,那就不管它~~)
>>> bds = '10+6/5-4*2' # 表达式
>>> m = re.sub(r'([*+-/])', ' \1 ', bds) # 注意\1左右皆有一个空格!!
>>> m
'10 + 6 / 5 - 4 * 2'
[b]2. 替换字符中含参数[/b]
\g<1>
>>> bds = '10+6/5-4*2' # 表达式
>>> m = re.sub(r'([*+-/])', ' \g<1> ', bds)
>>> m
'10 + 6 / 5 - 4 * 2'
[b]3. 模式中也可含参数[/b]
\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?"
[b]4. 模式中也可含参数[/b] :命名组
(?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?"
[b]PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:[/b]
[b]JavaScript正则表达式在线测试工具:
[/b][url=http://tools.jb51.net/regex/javascript]http://tools.jb51.net/regex/javascript[/url]
[b]正则表达式在线生成工具:
[/b][url=http://tools.jb51.net/regex/create_reg]http://tools.jb51.net/regex/create_reg[/url]
更多关于Python相关内容可查看本站专题:《[url=http://www.1sucai.cn/Special/667.htm]Python正则表达式用法总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》
希望本文所述对大家Python程序设计有所帮助。