Rewriting a URL with RegEx

2019-09-13 11:52发布

问题:

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)]