re正则匹配re.match()

前言

re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
re.search 扫描整个字符串并返回第一个成功的匹配。

re.match

使用语法:

re.match(pattern, string, flags=0)

函数参数说明:

  • pattern 匹配的正则表达式
  • string 要匹配的字符串。
  • flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符,可选标志

match 使用示例

从起始位置开始匹配,没匹配到返回None

import re

# 在起始位置匹配
r1 = re.match("hello", "hello world!")
# 不在起始位置匹配
r2 = re.match("world", "hello world!")
print(r1) #返回match对象
print(r1.group())
print(r2)

运行结果

<re.Match object; span=(0, 5), match='hello'>
hello
None

其他基础写法

import re
# 基础写法二
str_c=re.compile('hello')
r1=str_c.match('hello,world')
print(r1.group())

#基础写法三
str_c=re.compile('hello')
r2=re.match(str_c,'hello,world')
print(r2.group())

运行结果

hello
hello
原文地址:https://www.cnblogs.com/lvhuayan/p/15259407.html