通过模块re
匹配字符串,如下,判断字符串str2
是否在str1
中
import re
str1 = "aabcd"
str2 = "abc"
match = re.compile(str2).search(str1).group()
print(match)
这样写,是为了代码的简洁,但是容易引起报错:AttributeError: 'NoneType' object has no attribute 'group'
,分析原因发现当匹配不到元素,之后又调用了group()方法造成的。因此,代码进一步优化:
import re
str1 = "aabd"
str2 = "abc"
match = re.compile(str2).search(str1)
if match:
print(match.group())
elif match == None:
print("无法匹配")