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

Python中的正则表达式函数和应用技巧

发布时间:2023-06-17 21:03:16

正则表达式是一种用于匹配和搜索文本模式的强大工具。Python中内置了re模块,提供了很多正则表达式函数和方法。本文将介绍Python中常用的正则表达式函数和一些应用技巧。

1. re.match()函数

re.match(pattern, string, flags=0)函数尝试从字符串的开头匹配一个模式。如果匹配成功,则返回一个匹配对象;否则返回None。

例如,查找字符串开头是否为"hello":

import re

str = "hello, world"

pattern = r"^hello"

matchObj = re.match(pattern, str)

if matchObj:

    print("matchObj.group():", matchObj.group())

else:

    print("No match!")

输出为:

matchObj.group(): hello

2. re.search()函数

re.search(pattern, string, flags=0)函数在字符串中搜索匹配项。如果匹配成功,则返回一个匹配对象;否则返回None。

例如,查找字符串中是否包含"world":

import re

str = "hello, world"

pattern = r"world"

searchObj = re.search(pattern, str)

if searchObj:

    print("searchObj.group():", searchObj.group())

else:

    print("No match!")

输出为:

searchObj.group(): world

3. re.findall()函数

re.findall(pattern, string, flags=0)函数在字符串中查找所有匹配项,并将它们作为一个列表返回。

例如,查找所有的数字:

import re

str = "one 1 two 2 three 3"

pattern = r"\d+"

findallObj = re.findall(pattern, str)

print(findallObj)

输出为:

['1', '2', '3']

4. re.sub()函数

re.sub(pattern, repl, string, count=0, flags=0)函数用替换字符串替换在字符串中找到的所有匹配项。如果没有找到匹配项,则返回原始字符串。

例如,将字符串中所有的空格替换为逗号:

import re

str = "one 1 two 2 three 3"

pattern = r"\s+"

subObj = re.sub(pattern, ",", str)

print(subObj)

输出为:

one,1,two,2,three,3

应用技巧:

1. 字符串匹配

可以使用"."匹配任意字符,使用"^"匹配字符串开头,使用"$"匹配字符串结尾。

例如,查找以"hello"开头,以"world"结尾的字符串:

import re

str = "hello, world"

pattern = r"^hello.*world$"

matchObj = re.match(pattern, str)

if matchObj:

    print("matchObj.group():", matchObj.group())

else:

    print("No match!")

输出为:

matchObj.group(): hello, world

2. 分组匹配

使用"()"可以将模式分组,然后使用group()方法获取匹配到的组。

例如,匹配"hello, name"格式的字符串,使用分组匹配获取name:

import re

str = "hello, john"

pattern = r"^hello,\s(\w+)$"

matchObj = re.match(pattern, str)

if matchObj:

    print("matchObj.group():", matchObj.group())

    print("matchObj.group(1):", matchObj.group(1))

else:

    print("No match!")

输出为:

matchObj.group(): hello, john

matchObj.group(1): john

3. 非贪婪匹配

"*"和"+"默认是贪婪匹配,即尽可能多地匹配符合模式的字符串。可以在"*"和"+"后面加上"?"实现非贪婪匹配,即尽可能少地匹配符合模式的字符串。

例如,查找最短的以"a"开头,以"b"结尾的字符串:

import re

str = "abaabb"

pattern = r"^a.+?b$"

matchObj = re.match(pattern, str)

if matchObj:

    print("matchObj.group():", matchObj.group())

else:

    print("No match!")

输出为:

matchObj.group(): aba

总结:

通过本文的介绍,我们了解了Python中常用的正则表达式函数和一些应用技巧。正则表达式是一种非常强大的匹配和搜索工具,学习好正则表达式可以让我们在处理文本中更加高效地完成任务。