阅读量

原创教程,严禁转载。引用本文,请署名 Python中文网, http://www.zglg.work


92 正则最普通查找

最普通查找就是需要找啥就写啥,没有使用正则的规则。如下是关于小说《灿烂千阳》中的一段话,从中找出单词friendship,可能出现多次:

s = """
# Mariam is only fifteen 
# when she is sent to Kabul to marry the troubled and bitter Rasheed,
# who is thirty years her senior. 
# Nearly two decades later, 
# in a climate of growing unrest, tragedy strikes fifteen-year-old Laila, 
# who must leave her home and join Mariam's unhappy household. 
# Laila and Mariam are to find consolation in each other, 
# their friendship to grow as deep as the bond between sisters, 
# as strong as the ties between mother and daughter. 
# With the passing of time comes Taliban rule over Afghanistan, 
# the streets of Kabul loud with the sound of gunfire and bombs, 
# life a desperate struggle against starvation, brutality and fear, 
# the women's endurance tested beyond their worst imaginings. 
# Yet love can move a person to act in unexpected ways, 
# lead them to overcome the most daunting obstacles with a startling heroism. 
# In the end it is love that triumphs over death and destruction. 
# A Thousand Splendid Suns is an unforgettable portrait of a wounded country and
#  a deeply moving story of family and friendship. 
#  It is a beautiful, heart-wrenching story of an unforgiving time, 
#  an unlikely bond and an indestructible love.
"""

使用正则前,先导入re模块,再定义正则表达式,然后使用findall方法找出所有匹配

import re
pat = 'friendship'
result = re.findall(pat,s)
print(result) 

# 共找到两处:
# ['friendship', 'friendship']

以上就是使用正则的最普通例子。如果要找出前缀为grow的单词,比如可能为grows, growing 等,最普通查找实现起来就不方便。

然而,借助于下面介绍的元字符、通用字符和捕获组合起来,便能应对解决复杂的匹配查找问题。

上一个例子 下一个例子