什么是python re.match函数?
在这篇文章之中我们来了解一下关于python之中的正则表达式,有些朋友可能是刚刚接触到python这一编程语言,对于这一方面不是特别的了解,在接下来的文章之中我们来了解一下python中re.match函数,python re.match函数是python中常用的正则表达式处理函数。废话不多说,我们开始进入文章吧。
re.match函数:
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
函数的语法
re.match(pattern, string, flags=0)
函数参数说明:
立即学习“Python免费学习笔记(深入)”;
匹配成功re.match方法返回一个匹配的对象,否则返回None。
我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。
实例如下:
#!/usr/bin/python# -*- coding: UTF-8 -*- import reprint(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配
输出如下:
(0, 3)None
# !/usr/bin/pythonimport reline = "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 dogsmatchObj.group(1) : CatsmatchObj.group(2) : smarter