正则表达式中的flags

本文介绍了正则表达式中的四个重要标志:re.I 忽略大小写匹配,re.M 多行模式,re.S 使 '.' 匹配包括换行符的所有字符,以及 re.X 开启冗余模式,允许正则表达式的注释和空白。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

re.I    IGNORECASE, 忽略大小写的匹配模式
In [59]: s = 'hello World!'

In [60]: regex = re.compile("hello world!", re.I)

In [61]: regex.match(s).group()
Out[61]: 'hello World!'
re.M    MULTILINE,多行模式, 改变 ^ 和 $ 的行为
In [63]: s
Out[63]: 'first line\nsecond line\nthird line'

In [64]: pattern=re.compile(r'^\w+')

In [65]: re.findall(pattern,s)
Out[65]: ['first']

In [67]: pattern=re.compile(r'^\w+',re.M)

In [68]: re.findall(pattern,s)
Out[68]: ['first', 'second', 'third']
re.S   DOTALL,此模式下 '.' 的匹配不受限制,可匹配任何字符,包括换行符,也就是默认是不能匹配换行符
In [62]: s = '''first line
    ...: second line
    ...: third line'''

In [71]: regex=re.compile('.+',re.S)

In [73]: regex.findall(s)
Out[73]: ['first line\nsecond line\nthird line']

In [74]: regex=re.compile('.+')

In [75]: regex.findall(s)
Out[75]: ['first line', 'second line', 'third line']
re.X    VERBOSE,冗余模式, 此模式忽略正则表达式中的空白和#号的注释
email_regex = re.compile("[\w+\.]+@[a-zA-Z\d]+\.(com|cn)")

email_regex = re.compile("""[\w+\.]+  # 匹配@符前的部分
                            @  # @符
                            [a-zA-Z\d]+  # 邮箱类别
                            \.(com|cn)   # 邮箱后缀  """, re.X)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值