OILS / demo / cpython / regex_replace.py View on Github | oilshell.org

28 lines, 14 significant
1#!/usr/bin/env python3
2from __future__ import print_function
3
4import re
5import sys
6
7
8def ReplaceFunc(m):
9 return '[' + m.group(1) + ']'
10
11
12def ReplaceFuncDict(m):
13 return {'key': '[' + m.group(1) + ']'}
14
15
16def main(argv):
17 pat = re.compile(r'(\d+)')
18
19 #s = pat.sub(ReplaceFunc, 'foo 123 bar 456', ReplaceFunc)
20
21 s = pat.sub(ReplaceFunc, 'foo 123 bar 456')
22 print(s)
23
24 d = pat.sub(ReplaceFuncDict, 'foo 123 bar 456')
25 print(d)
26
27
28main(sys.argv)