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

Python中常用的正则表达式函数及实例分析

发布时间:2023-06-24 20:32:27

正则表达式是一种常用于匹配字符串的语法,通常用于文本处理、搜索、替换等。在Python中,可以使用re模块来使用正则表达式。

常用的正则表达式函数:

1. re.search(pattern, string, flags=0):在字符串中查找包含指定正则表达式模式的 个匹配项,并返回匹配的对象。

例如:

import re

pattern = r"hello"

string = "hello world"

match_obj = re.search(pattern, string)

if match_obj:

    print("find")

else:

    print("not find")

输出:find

2. re.findall(pattern, string, flags=0):返回字符串中所有匹配项组成的列表。

例如:

import re

pattern = r"\d+"

string = "hello 123 world 456"

match_objs = re.findall(pattern, string)

print(match_objs)

输出:['123', '456']

3. re.sub(pattern, repl, string, count=0, flags=0):用指定的替换字符串替换字符串中与正则表达式模式匹配的所有子字符串,并返回替换后新的字符串。

例如:

import re

pattern = r"\d+"

string = "hello 123 world 456"

new_string = re.sub(pattern, "**", string)

print(new_string)

输出:hello ** world **

实例分析:

1. 匹配IP地址

pattern = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

string = "192.168.1.1"

match_obj = re.search(pattern, string)

if match_obj:

    print(match_obj.group())

输出:192.168.1.1

2. 匹配邮箱地址

pattern = r"\w+@\w+\.\w+"

string = "abc@test.com"

match_obj = re.search(pattern, string)

if match_obj:

    print(match_obj.group())

输出:abc@test.com

3. 匹配手机号码

pattern = r"1[34578]\d{9}"

string = "13812345678"

match_obj = re.search(pattern, string)

if match_obj:

    print(match_obj.group())

输出:13812345678

总结:

正则表达式在Python中的应用非常广泛,可以用于字符串的匹配、搜索、替换等,常用的正则表达式函数有re.search()、re.findall()、re.sub()等。在实际开发中,需要根据需求选择合适的正则表达式来匹配字符串,以达到 的效果。