正则表达式匹配除外

时间:2011-09-27 14:54:58

标签: regex

我正在尝试匹配某些路径,但不是通过regexp匹配其他路径。我希望匹配以“/ profile /”开头的任何内容,而不是以下内容之一:

  • /简档/属性
  • /简档/撰
  • /简档/编辑

这是我正在尝试使用的正则表达式似乎不起作用:

^/profile/(?!attributes|essays|edit)$

例如,这些网址都没有与上述内容正确匹配:

  • /简档/亚光
  • /简档/ 127
  • /简档/ -591m!40v81,毫安/ ASDF?富=棒#1页

2 个答案:

答案 0 :(得分:4)

你需要说在字符串结尾之前可以有任何字符:

^/profile/(?!attributes|essays|edit).*$

删除字符串结尾锚也可以:

^/profile/(?!attributes|essays|edit)

您可能希望在负面预测中更加严格,以避免排除/profile/editor

^/profile/(?!(?:attributes|essays|edit)$)

答案 1 :(得分:1)

评论难以阅读代码,所以这是我的答案格式很好

def mpath(path, ignore_str = 'attributes|essays|edit',anything = True):
    any = ''
    if anything:
        any = '.*?'
    m = re.compile("^/profile/(?!(?:%s)%s($|/)).*$" % (ignore_str,any) )
    match = m.search(path)
    if match:
        return match.group(0)
    else:
        return ''