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

Python中的正则表达式:re库的常用函数及实例解析

发布时间:2023-06-10 20:04:57

Python中的正则表达式用于匹配字符串中的符合特定规则的文本,是一种高级文本匹配技术。Python中的re库提供了一系列函数来支持正则表达式的处理。本文将介绍re库的常用函数及实例解析。

1. re.match()函数

match()函数用于检查字符串是否以指定的模式开头。

实例:

import re

str = "hello world"

matchObj = re.match( r'hello', str)

if matchObj:

   print ("matches")

else:

   print ("not matches")

输出结果:

matches

2. re.search()函数

search()函数用于在字符串中查找符合特定规则的文本。

实例:

import re

str = "hello world"

searchObj = re.search( r'world', str)

if searchObj:

   print ("matches")

else:

   print ("not matches")

输出结果:

matches

3. re.findall()函数

findall()函数用于在字符串中找到所有符合特定规则的文本,并以列表的形式返回。

实例:

import re

str = "hello world"

findObj = re.findall( r'o', str)

print(findObj)

输出结果:

['o', 'o']

4. re.sub()函数

sub()函数用于替换字符串中符合特定规则的文本。

实例:

import re

str = "hello world"

subObj= re.sub( r'world', 'python', str)

print (subObj)

输出结果:

hello python

5. re.split()函数

split()函数用于将字符串从符合特定规则的地方切割成多个子串,并以列表的形式返回。

实例:

import re

str = "hello world"

splitObj = re.split( r' ', str)

print (splitObj)

输出结果:

['hello', 'world']

以上就是Python中的re库常用函数及实例解析,希望可以对大家有所帮助。