修改正则表达式

时间:2014-03-11 07:09:08

标签: python regex string function conditional-statements

我有几个字符串可以匹配某些表达式,我希望在介词之后匹配和提取2个单词以及preps本身..而且它们也做得很好。但是我需要修改正则表达式,以防万一“" to"在介词之后出现,正则表达式将提取介词后跟3个单词(而不是默认的2个单词......) 这是一个详细说明的例子:

str1 = " that place is near oberoi mall"
str2 = " that place is next to oberoi mall"

预期结果: -
res1 = "near oberoi mall" #extract准备后的2个单词(默认情况)
res2 = "next to oberoi mall" #extract准备好后跟3个单词(如果"到"介词后面)

我做了什么?

def landmark(str):
    preps = ['near','off','next','across','opposite','behind','above','ahead']
    words = "|".join(re.escape(line.rstrip()) for line in preps)
    p1 = re.compile(r'(?:{})\s(\w+|\d+\w+)\s\w+'.format(words))
    q =re.search(p1,str)
    if q is None:
       return ""
    else:
        return q.group()

我的preps在名为preps的列表中 返回2个单词很好,所以我得到了

res1 = "near oberoi mall"

res2 = "next to oberoi" #this变得不完整

我尝试了什么?
在这里:

p1 = re.compile(r'(?:{}(?:to)?)\s(\w+|\d+\w+)\s\w+'.format(words))  

*注意可选(?:to)?我补充说。那里有一些小问题..请帮忙。

1 个答案:

答案 0 :(得分:1)

这适用于您的示例:

>>> p1 = re.compile(r'(?:%s)\s((?:to\s)?(\w+|\d+\w+)\s\w+)' % words)
>>> dd = re.search(p1,str1)
>>> dd.group()
'near oberoi mall'
>>> cc = re.search(p1,str2)
>>> cc.group()
'next to oberoi mall'
相关问题