首页 文章

正则表达式匹配“wap”不在“html”之前

提问于
浏览
0

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

在'html'或通配符mimetype之前的 Headers 中出现'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

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

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

    阅读不愉快,但它应该工作 .

    Rubular

  • 2

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

    (?<!html.*?)wap
    

相关问题