一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python正则表达式中flags参数代码实例

时间:2022-04-01 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Python正则表达式中flags参数代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

flags参数

re.I

IGNORECASE

忽略字母大小写

re.L

LOCALE

影响 “w, “W, “b, 和 “B,这取决于当前的本地化设置。

re.M

MULTILINE

使用本标志后,‘^’和‘$’匹配行首和行尾时,会增加换行符之前和之后的位置。

re.S

DOTALL

使 “.” 特殊字符完全匹配任何字符,包括换行;没有这个标志, “.” 匹配除了换行符外的任何字符。

re.X

VERBOSE

当该标志被指定时,在 RE 字符串中的空白符被忽略,除非该空白符在字符类中或在反斜杠之后。

它也可以允许你将注释写入 RE,这些注释会被引擎忽略;

注释用 “#”号 来标识,不过该符号不能在字符串或反斜杠之后。

忽略大小写

import re
text = '我爱Python我爱python'
pat1 = 'p'
# search
r1 = re.findall(pattern=pat1, string=text, flags=re.I)
print(r1)

[‘P’, ‘p’]

多行模式

import re
text = '我爱数学n我爱Pythonn我爱python'
pat1 = '^我'
# search
r1 = re.findall(pattern=pat1, string=text)
r2 = re.findall(pattern=pat1, string=text, flags=re.M)
print(r1)
print(r2)

[‘我’]

[‘我’, ‘我’, ‘我’]

匹配任何字符

import re
text = '''
我爱Python
我爱pandas
'''
pat1 = '.我'
# search
r1 = re.findall(pattern=pat1, string=text, flags=re.S)
print(r1)
r2 = re.findall(pattern=pat1, string=text)
print(r2)

[’n我’, ‘n我’]

[]

补充:正则表达式中的flags

MULTILINE,多行模式, 改变 ^ 和 $ 的行为

In [63]: s
Out[63]: 'first linensecond linenthird 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 linensecond linenthird 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-Zd]+.(com|cn)")
 
email_regex = re.compile("""[w+.]+  # 匹配@符前的部分
                            @  # @符
                            [a-zA-Zd]+  # 邮箱类别
                            .(com|cn)   # 邮箱后缀  """, re.X)

热门栏目