Python中正则表达式函数示例
Python中的正则表达式函数十分强大,涵盖了多种操作,包括查找、替换、分割等。下面将逐一介绍这些函数以及示例。
1. re.search(pattern, string, flags=0)
search()函数用于在字符串中查找正则表达式的 个匹配项。它的参数包括正则表达式、待匹配字符串和标志位(可选)。该函数只返回 个匹配项,如果要搜索所有匹配项,请使用re.findall()。
示例:
import re
str1 = 'Today is a sunny day!'
pattern = 'sunny'
match = re.search(pattern, str1)
if match:
print(f'Found "{match.group()}" in "{str1}"')
else:
print('No match found')
输出:
Found "sunny" in "Today is a sunny day!"
2. re.findall(pattern, string, flags=0)
findall()函数用于在字符串中查找正则表达式的所有匹配项,并将它们作为列表返回。该函数返回所有匹配项,如果只需要 个匹配项,请使用re.search()。
示例:
import re str1 = 'red green blue yellow purple' pattern = '[a-z]+' matches = re.findall(pattern, str1) print(matches)
输出:
['red', 'green', 'blue', 'yellow', 'purple']
3. re.split(pattern, string, maxsplit=0, flags=0)
split()函数根据正则表达式在字符串中进行拆分,并返回拆分后的列表。maxsplit参数表示最大拆分次数(可选)。如果未指定maxsplit,则将拆分所有匹配项。
示例:
import re str1 = 'apple, pear, banana, orange, peach' pattern = ', ' fruits = re.split(pattern, str1) print(fruits)
输出:
['apple', 'pear', 'banana', 'orange', 'peach']
4. re.sub(pattern, repl, string, count=0, flags=0)
sub()函数用于在字符串中找到匹配项,并将其替换为指定的字符串。它的参数包括正则表达式、替换字符串、待匹配字符串和count(可选)表示最大替换次数。
示例:
import re str1 = 'one fish two fish red fish blue fish' pattern = 'fish' repl = 'cat' new_str = re.sub(pattern, repl, str1) print(new_str)
输出:
one cat two cat red cat blue cat
5. re.compile(pattern, flags=0)
compile()函数用于将模式字符串编译为正则表达式对象,以便以后可以快速重复使用。
示例:
import re
pattern = re.compile('[A-Z]+')
str1 = 'The Quick Brown Fox Jumps Over The Lazy Dog'
matches = pattern.findall(str1)
print(matches)
输出:
['T', 'Q', 'B', 'F', 'J', 'O', 'T', 'L', 'D']
6. re.match(pattern, string, flags=0)
match()函数类似于search()函数,但它只查找字符串的开头是否匹配正则表达式。
示例:
import re
str1 = '2021 is a good year'
str2 = 'It is 2021'
pattern = '2021'
match1 = re.match(pattern, str1)
match2 = re.match(pattern, str2)
if match1:
print(f'Found "{match1.group()}" in "{str1}"')
else:
print(f'No match found in "{str1}"')
if match2:
print(f'Found "{match2.group()}" in "{str2}"')
else:
print(f'No match found in "{str2}"')
输出:
No match found in "2021 is a good year" Found "2021" in "It is 2021"
以上就是Python中常用的正则表达式函数及示例。在使用时,请注意正则表达式的语法和模式。正则表达式可以提高字符串处理的效率和灵活性,建议掌握它的基本使用方法。
