是否有更好的方法在python中返回匹配项

时间:2019-10-10 05:37:41

标签: python regex

我是Python和Regex的新手。 我正在尝试从文本中匹配一些模式,然后从匹配的模式返回一个子字符串。步骤如下。

  1. 确定文本是否与服务请求上的状态更新相对应,该字符串是以SRT开头的字符串,后跟4位数字,例如SRT0001,SRT0002等。
  2. 如果满足以上条件,则返回匹配文本中提到的请求号(SRT0001等)。例如:如果文本为“希望您今天过得愉快。我需要更新SRT0001”

在这种情况下,我的代码需要匹配模式并返回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)看起来非常复杂且多余。无论如何,我可以做得更好吗?

0 个答案:

没有答案