正则表达式_帮助手册_CodingPark编程公园

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))


在这里插入图片描述

原创文章 35 获赞 22 访问量 3009

猜你喜欢

转载自blog.csdn.net/weixin_38411989/article/details/105422401
今日推荐