使用 RegEx 重写 URL [英] Rewriting a URL with RegEx

查看:49
本文介绍了使用 RegEx 重写 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正则表达式问题.考虑以下网址:

http://ab.cdefgh.com/aa-BB/index.aspx

我需要一个查看aa-BB"的正则表达式,如果没有匹配多个特定值,例如:

rr-GGVV-VVYY-YYZZ-ZZ

那么 URL 应该重定向到某个地方.例如:http://ab.cdefgh.com/notfound.aspx

在 web.config 中,我有 urlrewrite 规则.我需要知道什么正则表达式将在标签之间.

 <规则><url>?</url><rewrite>http://ab.cdefgh.com/notfound.aspx</rewrite></规则></urlrewrites>

解决方案

假设您不关心替换模式在域名或目录结构的其他级别中的可能性,则应选择您感兴趣的模式:

http:\/\/ab\.cdefgh\.com\/(?:aa\-BB|rr\-GG|vv\-VV|yy\-YY|zz\-ZZ)\/索引\.aspx

其中 aa-BB 等模式使用 | 运算符简单地或"连接在一起.

为了进一步分解,所有 /.- 字符都需要用 \ 转义 以防止正则表达式将它们解释为语法.(?: 表示法意味着将被或"的事物分组而不将其存储在反向引用变量中(如果您不关心保留选定的值,这将提高效率).

这是一个演示的链接(也许这可以帮助您在此处使用正则表达式以准确获得您想要的字符组合)

http://rubular.com/r/UfB65UyYrj

I have a RegEx problem. Consider the following URL:

http://ab.cdefgh.com/aa-BB/index.aspx

I need a regular expression that looks at "aa-BB" and, if it doesn't match a number of specific values, say:

rr-GG
vv-VV
yy-YY
zz-ZZ

then the URL should redirect to some place. For example: http://ab.cdefgh.com/notfound.aspx

In web.config I have urlrewrite rules. I need to know what the regex would be between the tags.

 <urlrewrites>
      <rule>
        <url>?</url>
        <rewrite>http://ab.cdefgh.com/notfound.aspx</rewrite>
      </rule>
 </urlrewrites>

解决方案

Assuming you don't care about the potential for the replacement pattern to be in the domain name or some other level of the directory structure, this should select on the pattern you're interested in:

http:\/\/ab\.cdefgh\.com\/(?:aa\-BB|rr\-GG|vv\-VV|yy\-YY|zz\-ZZ)\/index\.aspx

where the aa-BB, etc. patterns are simply "or"ed together using the | operator.

To further break this apart, all of the /, ., and - characters need to be escaped with a \ to prevent the regex from interpreting them as syntax. The (?: notation means to group the things being "or"ed without storing it in a backreference variable (this makes it more efficient if you don't care about retaining the value selected).

Here is a link to a demonstration (maybe this can help you play around with the regex here to get to exactly which character combinations you want)

http://rubular.com/r/UfB65UyYrj

这篇关于使用 RegEx 重写 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆