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

Python正则表达式函数-Search、Match、Findall、Split、Sub

发布时间:2023-06-14 09:45:37

Python正则表达式函数包括Search、Match、Findall、Split和Sub。这些函数都是由Python内置的re模块提供的。正则表达式是一种用来描述字符串模式的语言,可以帮助我们匹配、搜索、分割和替换文本中的单词、句子和段落。下面我们来逐一介绍这些函数。

1. Search函数

Search函数用来在字符串中查找和匹配正则表达式,返回 个匹配的结果。如果没有匹配到,则返回None。下面是一个简单的例子:

import re

pattern = r"Python"
text = "I love Python programming language"

match_obj = re.search(pattern, text)

if match_obj:
    print("Match found at position: ", match_obj.start())
else:
    print("Match not found")

输出结果为:

Match found at position:  7

2. Match函数

Match函数与Search函数类似,但是它只在字符串的开始位置匹配正则表达式。如果没有匹配到,则返回None。下面是一个例子:

import re

pattern = r"^Python"
text = "Python is a popular programming language"

match_obj = re.match(pattern, text)

if match_obj:
    print("Match found at position: ", match_obj.start())
else:
    print("Match not found")

输出结果为:

Match found at position:  0

3. Findall函数

Findall函数用来查找字符串中所有匹配正则表达式的子串,并返回一个由这些子串组成的列表。下面是一个例子:

import re

pattern = r"\d+"
text = "I have 2 cats and 3 dogs"

match_obj = re.findall(pattern, text)

print(match_obj)

输出结果为:

['2', '3']

4. Split函数

Split函数用来根据正则表达式的匹配结果分割字符串,并返回一个由分割出的子串组成的列表。下面是一个例子:

import re

pattern = r"\W+"
text = "Python is a popular programming language, used for web development."

match_obj = re.split(pattern, text)

print(match_obj)

输出结果为:

['Python', 'is', 'a', 'popular', 'programming', 'language', 'used', 'for', 'web', 'development', '']

5. Sub函数

Sub函数用来替换字符串中匹配正则表达式的子串,返回替换后的字符串。下面是一个例子:

import re

pattern = r"\d+"
text = "I have 2 cats and 3 dogs"

new_text = re.sub(pattern, "0", text)

print(new_text)

输出结果为:

I have 0 cats and 0 dogs

综上所述,Python正则表达式函数Search、Match、Findall、Split和Sub是非常常用的字符串处理函数,它们能够帮助我们快速地匹配、搜索、分割和替换文本中的子串。对于需要对文本进行处理的Python开发者来说,掌握这些函数的使用方法是非常重要的。