Home >Backend Development >Python Tutorial >What is the python re.match function? (Example analysis)

What is the python re.match function? (Example analysis)

乌拉乌拉~
乌拉乌拉~Original
2018-08-20 17:56:5921812browse

In this article, we will learn about regular expressions in python. Some friends may have just come into contact with the programming language python and do not have a special understanding of this aspect. In the following article, Let's take a look at the re.match function in python. The python re.match function is a commonly used regular expression processing function in Python. Without further ado, let’s get started with the article.

re.match function:

re.match attempts to match a pattern from the starting position of the string. If the matching is not successful at the starting position, match() Just return none.

Function syntax

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

Function parameter description:

What is the python re.match function? (Example analysis)

The re.match method returns a match if the match is successful object, otherwise None is returned.

We can use group(num) or groups() matching object function to get the matching expression.

What is the python re.match function? (Example analysis)

The example is as follows:

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

The output is as follows:

(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!!"

The output of the above example is as follows:

matchObj.group() :  Cats are smarter than dogs

matchObj.group(1) :  Cats

matchObj.group(2) :  smarter

The above is this All the content described in this article, this article mainly introduces the relevant knowledge of the re.match function in python. I hope you can use the information to understand the above content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of What is the python re.match function? (Example analysis). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn