当前位置:Gxlcms > Python > 什么是pythonre.match函数?(实例解析)

什么是pythonre.match函数?(实例解析)

时间:2021-07-01 10:21:17 帮助过:112人阅读

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

re.match函数

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

函数的语法

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

函数参数说明:

正则表达式.png

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

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

方法.png

实例如下:

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import re
  4. print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配
  5. print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配

输出如下:

  1. (0, 3)None
  1. # !/usr/bin/python
  2. import re
  3. line = "Cats are smarter than dogs"
  4. matchObj = re.match(r'(.*) are (.*?) .*', line, re.M | re.I)
  5. if matchObj:
  6. print "matchObj.group() : ", matchObj.group()
  7. print "matchObj.group(1) : ", matchObj.group(1)
  8. print "matchObj.group(2) : ", matchObj.group(2)
  9. else:
  10. print "No match!!"

以上实例输出如下:

  1. matchObj.group() : Cats are smarter than dogs
  2. matchObj.group(1) : Cats
  3. matchObj.group(2) : smarter

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

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

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

人气教程排行