Rewriting a URL with RegEx

不打扰是莪最后的温柔 提交于 2019-12-11 16:55:48

问题


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>

回答1:


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




回答2:


Will this help?

^([a-z])\1-([A-Z])\2.*

It matches:

uu-FF/
aa-BB/
bb-CC/index

But not

aaBB
asdf
ba-BB
aA-BB

(Edit based on comment)

Just pipe delimit your desired urls inside of () and escaping special chars.

Eg.

^(xx-YY|yy-ZZ|aa-BB|goodStuff)/.*

But, I think you might actually want the following which matches anything other than the urls that you specify, so that all else goes to notfound.aspx:

^[^(xx-YY|yy-ZZ|aa-BB|goodStuff)]/.*



回答3:


Assuming you want anything but xx-XX, yy-YY and zz-ZZ to redirect:

[^(xx\-XX)|(yy\-YY)|(zz\-ZZ)]


来源:https://stackoverflow.com/questions/6432376/rewriting-a-url-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!