在这篇文章之中我们来了解一下关于python之中的正则表达式,有些朋友可能是刚刚接触到python这一编程语言,对于这一方面不是特别的了解,在接下来的文章之中我们来了解一下python中re.match函数,python re.match函数是Python中常用的正则表达式处理函数。废话不多说,我们开始进入文章吧。

re.match函数

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

函数的语法

re.match(pattern, string, flags=0)
登录后复制

函数参数说明:

什么是python re.match函数?(实例解析)-LMLPHP

匹配成功re.match方法返回一个匹配的对象,否则返回None。

我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。

什么是python re.match函数?(实例解析)-LMLPHP

实例如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
 
import re
print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.match('com', 'www.runoob.com'))         # 不在起始位置匹配
登录后复制

输出如下:

(0, 3)None
登录后复制
 # !/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match(r'(.*) are (.*?) .*', line, re.M | re.I)
if matchObj:
    print "matchObj.group() : ", matchObj.group()
    print "matchObj.group(1) : ", matchObj.group(1)
    print "matchObj.group(2) : ", matchObj.group(2)
else:
    print "No match!!"
登录后复制

以上实例输出如下:

matchObj.group() :  Cats are smarter than dogs

matchObj.group(1) :  Cats

matchObj.group(2) :  smarter
登录后复制

以上就是本篇文章所讲述的所有内容,这篇文章主要介绍了python中re.match函数的相关知识,希望你能借助资料从而理解上述所说的内容。希望我在这片文章所讲述的内容能够对你有所帮助,让你学习python更加轻松。

更多相关知识,请访问Work网Python教程栏目。

以上就是什么是python re.match函数?(实例解析)的详细内容,更多请关注Work网其它相关文章!

08-25 08:46