正则表达式

正则表达式对于处理字符串非常方便

1 match()

import re

# match()函数如果匹配返回一个对象,否则返回None
k = re.match('ww', 'wwadcd')
print(k)
# 如果为非空,将正则化表达式输出,即第一个参数输出
print(k.group())

# group()和group(0)是一样的,group(1)表示输出正则表达式中第一个括号里的内容
line = "Cats are smarter than dogs"
r = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
print(r)
print(r.group())
print(r.group(0))
print(r.group(1))
print(r.group(2))

# 注意 .*可以表示任意字符串,因为其表示有*个.,而*是任意的 .可以代表任意一个字符,整体表示有任意个.
print(re.match('.*b', 'baaaab').group())
# 注意c*是一个整体这里*号取了,表示有0个c,即整体没有c
print(re.match('c*a*c', 'acc').group())

# <_sre.SRE_Match object; span=(0, 2), match='ww'>
# ww
# <_sre.SRE_Match object; span=(0, 26), match='Cats are smarter than dogs'>
# Cats are smarter than dogs
# Cats are smarter than dogs
# Cats
# smarter
# baaaab
# ac
View Code

参考:https://www.liaoxuefeng.com/wiki/897692888725344/923056128128864

https://www.runoob.com/python/python-reg-expressions.html#flags

https://www.jb51.net/article/143366.htm

原文地址:https://www.cnblogs.com/xxswkl/p/11377702.html