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

Python中如何使用正则表达式进行字符串匹配与替换

发布时间:2023-12-25 19:03:46

在Python中,我们可以使用re模块来使用正则表达式进行字符串匹配和替换。re模块提供了一组函数,可以通过正则表达式来查找、匹配和替换字符串。

下面是一些常用的re模块函数:

1. re.match(pattern, string, flags=0):从字符串的起始位置进行匹配,如果匹配成功返回匹配对象,否则返回None。

import re

pattern = r'hello'
string = 'hello world'
result = re.match(pattern, string, flags=0)
print(result)  # <re.Match object; span=(0, 5), match='hello'>

2. re.search(pattern, string, flags=0):从字符串中查找 个匹配项,如果匹配成功返回匹配对象,否则返回None。

import re

pattern = r'world'
string = 'hello world'
result = re.search(pattern, string, flags=0)
print(result)  # <re.Match object; span=(6, 11), match='world'>

3. re.findall(pattern, string, flags=0):在字符串中查找所有匹配项,并以列表的形式返回。

import re

pattern = r'l'
string = 'hello world'
result = re.findall(pattern, string, flags=0)
print(result)  # ['l', 'l', 'l']

4. re.sub(pattern, repl, string, count=0, flags=0):将字符串中所有匹配正则表达式的子串进行替换。

import re

pattern = r'l'
string = 'hello world'
repl = 'x'
result = re.sub(pattern, repl, string, count=0, flags=0)
print(result)  # hexxo worxd

5. re.split(pattern, string, maxsplit=0, flags=0):按照正则表达式匹配的地方分割字符串,并以列表的形式返回分割后的子串。

import re

pattern = r'\s'
string = 'hello world'
result = re.split(pattern, string, maxsplit=0, flags=0)
print(result)  # ['hello', 'world']

除了上述函数,re模块还支持一些特殊字符和匹配模式,例如元字符、字符类、重复限定符等,可以用来进行更复杂的字符串匹配和替换。

以下是一个使用正则表达式进行字符串匹配和替换的例子:

import re

# 匹配手机号码
def match_phone_number(string):
    pattern = r'^1[3-9]\d{9}$'
    result = re.match(pattern, string)
    if result:
        print('手机号码合法')
    else:
        print('手机号码不合法')

# 替换字符串中的敏感词
def replace_sensitive_word(string):
    pattern = r'(敏感词1|敏感词2|敏感词3)'
    repl = '***'
    result = re.sub(pattern, repl, string)
    print(result)

# 测试
phone_number = '13912345678'
match_phone_number(phone_number)

sensitive_string = '这是一条包含敏感词1的字符串'
replace_sensitive_word(sensitive_string)

在上面的例子中,我们通过正则表达式匹配了一个手机号码,并进行了敏感词替换。运行结果如下:

手机号码合法
这是一条包含***的字符串

通过re模块提供的函数和正则表达式,我们可以方便地进行字符串的匹配和替换,扩展了字符串处理的能力。使用正则表达式可以灵活、高效地处理各种字符串问题。