我是Python和Regex的新手。 我正在尝试从文本中匹配一些模式,然后从匹配的模式返回一个子字符串。步骤如下。
在这种情况下,我的代码需要匹配模式并返回SRT0001。到目前为止,我已经编写了返回SRT编号的代码,但是我想知道是否有更好的方法可以做到这一点?我的代码如下。
regex_1 = re.compile('(looking|want|need|seek|seeking|request|requesting|get|please)'
'\s([^.?]{0,6})(\s{0,1})'
'(status|update)\s([^.?]{0,6})(\s{0,1})'
'(srt[0-9]{4})')
'(srt[0-9]{4})\?')
regex_2 = re.compile('(can|would|could)?\s?'
'(you|your|anyone|someone)+\s?'
'(guys|people|fellows|team)?\s?(please)?\s?'
'(let|tell)?\s?'
'(us|me|my team|our people)?\s?'
'(know|update)\s?'
'(of|on|about|regarding)\s?'
'(status|the status)\s'
'(of|of this|of the|of the below)?\s?'
'(sr|request|service request|srt)?\s?'
'([:-;])?\s?'
'(srt[0-9]{4})\?')
def status_update_regex(email):
email = email.lower()
if regex_1.search(email) != None:
return re.search('srt[0-9]{4}',str(regex_1.search(email))).group(0)
elif regex_2.search(email) !=None:
return re.search('srt[0-9]{4}',str(regex_2.search(email))).group(0)
else:
return 0
regex_1和regex_2尝试检查给定的文本是否是来自用户的有关服务请求的查询。 我似乎不存在匹配一些简单模式的问题,但是status_update_regex()中的返回值(应该是SRTnumber)看起来非常复杂且多余。无论如何,我可以做得更好吗?