re.search():匹配整个字符串,并返回第一个成功的匹配。如果匹配失败,则返回None 

pattern: 匹配的规则,

string : 要匹配的内容,

flags 标志位 这个是可选的,就是可以不写,可以写, 比如要忽略字符的大小写就可以使用标志位

flags : 可选,表示匹配模式,比如忽略大小写,多行模式等,具体参数为:

  1. re.I 忽略大小写
  2. re.L 表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境
  3. re.M 多行模式
  4. re.S 即为 . 并且包括换行符在内的任意字符(. 不包括换行符)
  5. re.U 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库
  6. re.X 为了增加可读性,忽略空格和 # 后面的注释

示例代码:【检查字符串是否以 "Long" 开头并以 "China" 结尾

import re

s = "Long live the people's Republic of China"
ret = re.search("^Long.*China$", s)

print(ret)
print(ret.group())
print(ret[0])

运行结果:

 示例代码:【在字符串中搜索第一个空白字符

import re

s = "Long live the people's Republic of China"
ret = re.search("\s", s)

print(ret)
print(ret.start())

运行结果:

示例代码:【如果search未匹配到,返回None】

import re

s = "Long live the people's Republic of China"
ret = re.search("USA", s)

print(ret)

运行结果:

 示例代码:【忽略大小写】

import re

s = "Long live the people's Republic of China"
# ret1 = re.search('long', s)  这行代码直接报错
ret1 = re.search('l', s)
print(ret1)
print(ret1.span())
print(ret1.string)
print(ret1.group())

print("*" * 50)

ret2 = re.search('long', s, re.I)
print(ret2)
print(ret2.span())
print(ret2.string)
print(ret2.group())

运行结果:

示例代码:【group()的使用】 

import re

s = 'abc123def456ghi789'
ret_compile = re.compile("([a-z]*)([0-9]*)([a-z]*)")
print(ret_compile)

ret = ret_compile.search(s)
print(ret)
print(ret.group())
print(ret.group(0))  # group()和group(0) 一样匹配的是整体
print(ret.group(1))  # 匹配第1个小括号的内容
print(ret.group(2))  # 匹配第2个小括号的内容
print(ret.group(3))  # 匹配第3个小括号的内容

运行效果:

 示例代码:【group()分组的使用】

import re

s = 'abc123def456ghi789'
ret_compile = re.compile("(?P<num1>[a-z]*)(?P<num2>[0-9]*)(?P<num3>[a-z]*)")
print(ret_compile)

ret = ret_compile.search(s)
print(ret)
print(ret.group())
print(ret.group(0))  # group()和group(0) 一样匹配的是整体
print(ret.group(1))  # 匹配第1个小括号的内容
print(ret.group(2))  # 匹配第2个小括号的内容
print(ret.group(3))  # 匹配第3个小括号的内容

print("*" * 100)

print(ret.group())
print(ret.group("num1"))  # 这里效果等同于group(1)
print(ret.group("num2"))  # 这里效果等同于group(3)
print(ret.group("num3"))  # 这里效果等同于group(3)

运行效果:

来源:IT之一小佬

物联沃分享整理
物联沃-IOTWORD物联网 » re.search()用法详解

发表评论