, 10)
print("-" * 15 + "finditer methods" + "-" * 15)
print("type of method: ", type(f_i))
for m1 in f_i: # m1 是 Match 对象
print('matching string: {}, position: {}'.format(m1.group(), m1.span()))
p = re.compile(r'[\s\,\;]+')
print("-" * 15 + "Split methods" + "-" * 15)
print("split a,b;c.d: ", p.split('a,b;; c d'))
p1 = re.compile(r'(\w+) (\w+)')
s1 = 'hello 123, hello 456'
def func(m):
return 'hi' + ' ' + m.group(2)
print("-" * 15 + "替换 methods" + "-" * 15)
print(p1.sub(r'hello world', s1)) # 使用 'hello world' 替换 'hello 123' 和 'hello 456'
print(p1.sub(r'\2 \1', s1)) # 引用分组
print(p1.sub(func, s1))
print(p1.sub(func, s1, 1)) # 最多替换一次
结果是:
---------------Match methods---------------
found strings: 12
start index of found strings: 3
end index of found strings: 5
Span length of found strigns: (3, 5)
---------------Search methods---------------
found strings: 12
start index of found strings: 3
end index of found strings: 5
Span length of found strigns: (3, 5)
---------------findall methods---------------
found strings: ['1', '2']
---------------finditer methods---------------
type of method: <class 'callable_iterator'>
matching string: 1, position: (3, 4)
matching string: 2, position: (7, 8)
---------------Split methods---------------
split a,b;c.d: ['a', 'b', 'c', 'd']
---------------替换 methods---------------
hello world, hello world
123 hello, 456 hello
hi 123, hi 456
hi 123, hello 456