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

Python正则表达式函数实例

发布时间:2023-07-06 11:34:25

正则表达式在Python中是通过re模块提供的函数来实现的。下面将介绍一些常用的正则表达式函数实例:

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

该函数尝试从字符串的开头开始匹配一个模式,如果字符串的开头不匹配模式,则返回None;如果匹配成功,则返回一个Match对象。

示例:

import re

string = "Hello World"
pattern = r"Hello"
result = re.match(pattern, string)
if result:
    print("匹配成功")
else:
    print("匹配失败")

输出:

匹配成功

2. re.search(pattern, string, flags=0)

该函数在字符串中搜索匹配指定模式的 个位置,如果匹配成功,则返回一个Match对象;如果匹配失败,则返回None。

示例:

import re

string = "Hello World"
pattern = r"World"
result = re.search(pattern, string)
if result:
    print("匹配成功")
else:
    print("匹配失败")

输出:

匹配成功

3. re.findall(pattern, string, flags=0)

该函数在字符串中搜索匹配指定模式的所有位置,并以列表的形式返回匹配结果。

示例:

import re

string = "Hello World"
pattern = r"\w+"
result = re.findall(pattern, string)
print(result)

输出:

['Hello', 'World']

4. re.sub(pattern, repl, string, count=0, flags=0)

该函数在字符串中搜索匹配指定模式的所有位置,并使用repl参数指定的替换字符串替换它们。如果count参数非零,则只替换count个匹配。

示例:

import re

string = "Hello World"
pattern = r"World"
repl = "Python"
result = re.sub(pattern, repl, string)
print(result)

输出:

Hello Python

5. re.split(pattern, string, maxsplit=0, flags=0)

该函数根据指定的模式对字符串进行分割,并将分割结果以列表的形式返回。

示例:

import re

string = "Hello World"
pattern = r" "
result = re.split(pattern, string)
print(result)

输出:

['Hello', 'World']

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