Python正则表达式
1 基础语法
2 练习工具推荐
正则表达式在线验证工具http://regexr.com/
3 正则表达式挑战(过关类)
https://alf.nu/RegexGolf
4 案例
import re
'''
将正则表达式编译成Pattern对象
'''
pattern = re.compile(r'hello.*\!')
match = pattern.match('hello, hanxiaoyang! How are you?')
m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello hanxiaoyang!')
if match:
print(match.group())
print(match.groups())
print(m.group(1,2,3))
print(m.groups())
'''
切分
'''
# 模板
pi = re.compile(r'\d')
# 用这个模板切
text = pi.split('one1two2three3four4')
print(text)
piPlus = re.compile(r'\d')
# 用这个模板切
text2 = piPlus.findall('one1two2three3four4')
print(text2)
'''
替换
'''
p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello hanxiaoyang!'
print(p.sub(r'\2 \1', s))
def func(n):
return n.group(1).title() + ' ' + n.group(2).title()
print(p.subn(func, s))