日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python正則表達式中flags參數(shù)的實例詳解_python

作者:小基基o_O ? 更新時間: 2022-06-04 編程語言

flags參數(shù)

re.I
? ? IGNORECASE
? ? 忽略字母大小寫

re.L
? ? LOCALE
? ? 影響 “w, “W, “b, 和 “B,這取決于當前的本地化設(shè)置。

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 = '我愛數(shù)學(xué)\n我愛Python\n我愛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 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)

總結(jié)

原文鏈接:https://blog.csdn.net/Yellow_python/article/details/80543937

欄目分類
最近更新