欢迎访问宙启技术站
智能推送

Python中的正则表达式函数的使用方法

发布时间:2023-06-23 09:55:15

正则表达式是一个强大的工具,用于搜索和替换文本中的模式。在Python中,re模块提供了正则表达式函数的功能。本文将介绍Python中正则表达式函数的使用方法。

1. re.match函数

re.match函数尝试从字符串的开头匹配一个正则表达式。如果匹配成功,返回一个匹配对象;否则返回None。

import re

str = "Hello, world!"
matchObj = re.match(r'Hello', str)
if matchObj:
    print("matchObj.group() : ", matchObj.group())
else:
    print("No match!!")

输出:

matchObj.group() :  Hello

2. re.search函数

re.search函数在字符串中搜索给定的正则表达式,返回 个匹配项。如果没有匹配,返回None。

import re

str = "Hello, world!"
searchObj = re.search(r'world', str)
if searchObj:
    print("searchObj.group() : ", searchObj.group())
else:
    print("Nothing found!!")

输出:

searchObj.group() :  world

3. re.findall函数

re.findall函数返回字符串中所有与正则表达式匹配的子串。如果没有匹配,返回空列表。

import re

str = "Hello, world!"
findallObj = re.findall(r'\w+', str)
print(findallObj)

输出:

['Hello', 'world']

4. re.sub函数

re.sub函数用给定的正则表达式匹配字符串,并用指定的字符串替换匹配的部分。它返回经过替换后的新字符串。

import re

str = "Hello, world!"
subObj = re.sub(r'world', 'python', str)
print(subObj)

输出:

Hello, python!

5. re.split函数

re.split函数根据指定的正则表达式,将字符串分割为单词列表。

import re

str = "Hello, world!"
splitObj = re.split(r'\W+', str)
print(splitObj)

输出:

['Hello', 'world', '']

这是因为正则表达式r'\W+'匹配所有非字母数字字符。

以上就是Python中正则表达式函数的使用方法,通过这些函数,可以方便地对字符串使用正则表达式进行匹配、搜索、替换和分割操作。