我理解re.search返回一个匹配对象re.search(pattern, string, flags=0)我在测试这场比赛是否成功。然后检索字符串
# matchTest.py --- testing match object returns
import re
# expected_pattern = suburbRegex
suburbRegex = "(?s)(,_S+s)"
# line leading up to and including expected_pattern
mostOfLineRex = "(?s)(^.+,S+)"
# expected_pattern to end of line
theRestRex = "(?s),_S+sw+s(.+)"
fileLines = ['173 ANDREWS John Frances 20 Bell_Road,_Sub_urbia Semi Retiredn']
for fileLine in fileLines:
result = re.search(suburbRegex, fileLine)
# print(type(result)) # re.Match
if(result):
patResult = re.search(suburbRegex, fileLine).group(0)
# print(patResult)
# print(type(patResult)) # str
# print(type(re.search(suburbRegex, fileLine).group(0))) # str
start = re.search(mostOfLineRex, fileLine)
if(start):
start = re.search(mostOfLineRex, fileLine).group(0)
# print(start)
print(type(start)) # str
end = re.search(theRestRex, fileLine)
if(end):
end = re.search(theRestRex, fileLine).group(0)
# print(end)
print(type(end)) # str
newFileLine = start + ' ' + end
else:
print("The listing does not have a suburb!")
# File "~matchTest.py", line 31, in <module>
# newFileLine = start + ' ' + end
# TypeError: can only concatenate str (not "NoneType") to str
我检查了start &最后是<class 'str'>
,为什么会出现NoneType
错误?
您对re.search()
的返回值有一个错误的假设
>>> matches = re.search(r'[0-9]+', "testme 9"); matches; type(matches)
<re.Match object; span=(7, 8), match='9'>
<class 're.Match'>
>>> matches = re.search(r'[0-9]+', "testme"); matches; type(matches)
<class 'NoneType'>
这解释了你的错误时,试图连接start
" "
和end
。