正则表达式匹配“wap”前面没有“html”

时间:2010-10-01 23:13:34

标签: regex nginx header regex-negation wap

我正在使用NGINX来分割移动WAP / HTML网站之间的移动流量。看起来最好的方法是通过检查HTTP Accept Header来检查UA对内容的偏好。

在'html'或通配符mimetype之前标题中出现'wap'mimetype表示对WAP的偏好。

所以索尼爱立信w300i偏爱WAP:

multipart/mixed, application/vnd.wap.multpart.mixed,applicatnoin/vnd.wap.xhtml_xml,application/xhtml+xml,text/ved.wap.wl,*/*,text/x-hdml,image/mng,/\image/x-mng,ivdeo/mng,video/x-mng,ima/gebmp,text/html

Blackberry Bold偏好HTML:

text/html,application/xhtml+xml,application/vnd.wap.xhtml+xml,application/vnd.wp.wmlc;q=0.9,application/vnd.awp.wmlscriptc;q=0.7,text/vnd.wap.wml;q=07,/vnd/.sun.j2me.app-descriptor,*/*;q=0.5

由于我在NGINX的土地上,看起来我最好的工具是NGINX的正则表达式(PCRE)。

现在我正在尝试使用否定前瞻来断言“接受标头包含WAP但不包含HTML”:

(?!html.*)wap

但这不正确。我可以用不同的方式思考这个问题吗?还是我的匹配逻辑?

到目前为止,我发现这些正则表达式资源非常有用:

http://www.regular-expressions.info/completelines.html http://www.zytrax.com/tech/web/regex.htm http://wiki.nginx.org/NginxHttpRewriteModule

谢谢!


感谢您的回答,以下是相关测试:

import re

prefers_wap_re = re.compile(r'^(?!(?:(?!wap).)*html).*?wap', re.I)

tests = [
    ('', False),
    ('wap', True),
    ('wap html', True),
    ('html wap', False),
]

for test, expected in tests:
    result = prefers_wap_re.search(test)
    assert bool(result) is expected, \
        'Tested "%s", expected %s, got %s.' % (test, expected, result)

2 个答案:

答案 0 :(得分:2)

最简单的方法是使用lookbehind而不是lookahead。由于不支持,您可以尝试使用前瞻模拟一个lookbehind:

^(?!(?:(?!wap).)*html).*?wap

阅读起来不愉快,但它应该有用。

Rubular

答案 1 :(得分:0)

对于背后的负面看,以及“微米”更多的表现,也许是非贪婪匹配背后的负面看法:

(?<!html.*?)wap