正则表达式中[\b],\b,\B的用法:

re模块中flags:

1.re.I
Ignorecase 忽略大小写
2.re.L
Locala-aware本地化识别匹配
3.re.M
Multiline 多行匹配,"^"与"$"匹配行首与行尾,会增加换行符之前和之后.
4.re.S
dotall 使"."特殊字符完全匹配任何字符,包括换行;没有这个标志,"."匹配除了换行符外的任何字符
5.re.X
verbose  当该标志被指定时,在 RE 字符串中的空白符被忽略,除非该空白符在字符类中或在反斜杠之后。
    它也可以允许你将注释写入 RE,这些注释会被引擎忽略;
    注释用 “#”号 来标识,不过该符号不能在字符串或反斜杠之后。

示例:

import re
#关于flags的设置

#1.忽略大小写
text = 'PYTHON  python'
p1 = 'p'
print('忽略大小写:',re.findall(p1,text,flags=re.I))

#2.多行模式
text = '我爱数学\n我爱Python\n我爱python'
pat1 = '^我'
r1 = re.findall(pattern=pat1, string=text)
r2 = re.findall(pattern=pat1, string=text, flags=re.M)
print('非多行匹配:',r1)
print('  多行匹配:',r2)

#匹配任何字符:
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)
##########################
忽略大小写: ['P', 'p']
非多行匹配: ['我']
  多行匹配: ['我', '我', '我']
包括换行符: ['\n我', '\n我']
不带换行符: []

re模块中sub用法:

​ 用于替换字符串中的匹配项

re.sub(pattern,repl,string,count=0,flags=0)

  • pattern 正则中的模式串

  • repl 替换的字符串,也可以是函数

  • string 要被查找替换的原始字符串

  • count 模式匹配后替换的最大次数,默认是0

    import re
    phone = "2004-959-559 # 这是一个国外电话号码"
    
    # 删除字符串中的 Python注释
    num = re.sub(r'#.*$', "", phone)
    print("电话号码是: ", num)
    #匹配电话号码
    num = re.sub(r'\D', "", phone)
    print("电话号码是: ", num)

re.compile:

​ compile函数用于编译正则表达式,生成一个正则表达式(pattern)对象,和findall,match与search函数使用.

re.compile(pattern[,flags])

import re


def main():
    content = 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'
    regex = re.compile('\w*o\w*')
    x = regex.findall(content)
    print(x)


if __name__ == '__main__':
    main()
# ['Hello', 'from', 'Chongqing', 'montain', 'to', 'you']

正则表达式关于[\b],\b,\B的区别:

  • [\b]匹配转义字符\b本身,匹配退格键\u0008
    
print(re.sub(re.compile(r"[\b]", re.S), "|", "That \bdang-to_ot_in' \b#!@\b#$ var\bmint's cost me $199.95!"))
##########################
That |dang-to_ot_in' |#!@|#$ var|mint's cost me $199.95!
  • \b 匹配字母或数字边界

    注意:\b属于匹配位置的元字符,一般作占位作用,而不被捕获,同属于匹配位置的还有匹配行起始位^和行结束位$

    匹配必须出现在 \w (字母数字)和 \W (非字母数字)字符之间的边界上

    print(re.sub(re.compile(r"\b", re.S), "|", "That \bdang-to_ot_in' \b#!@\b#$ var\bmint's cost me $199.95!"))
    ##################
    |That||dang|-|to_ot_in|'#!#$ |var|mint|'|s| |cost| |me| $|199|.|95|!
  • \B 匹配非字母和数字边界

    匹配不得出现在 \b 边界上

    print(re.sub(re.compile(r"\B", re.S), "|", "That \bdang-to_ot_in' \b#!@\b#$ var\bmint's cost me $199.95!"))
    ##############################
    T|h|a|t d|a|n|g-t|o|_|o|t|_|i|n'| |#|!|@|#|$| v|a|m|i|n|t's c|o|s|t m|e |$1|9|9.9|5!|

猜你喜欢

转载自www.cnblogs.com/Zhao159461/p/11366687.html