tags:

views:

511

answers:

5

Hi all,

I'm putting together some regexps to handle redirecting incoming links from an old site to the equivalent page on the new site. I'm hoping I can handle the following situation in the regexp so I don't have to do it on the back-end:

Incoming link: /reservations/inn_details.asp?num=717

Redirected link: /reservations/property-detail.aspx?pid=00717

As you can see, the original query string value of 717 needs to be 00717 in the redirected link. The rule is that these IDs all need to be five characters long in the redirected URL.

So my question is: is it possible within the regexp to figure out how many charactes the query string value is, and then add enough leading 0s to it to equal five characters?

I could do four separate regexps to cover cases where the value is 1, 2, 3 or 4 digits long, but it'd be much cooler do handle it all in one fell swoop!

Thanks, B.

+6  A: 

Unfortunately this isn't something you'll be able to handle with a regex alone. It seems to me that the easiest fix would be changing property-detail.aspx to do the zero-padding.

What I mean is, just have the regex redirect to "/reservations/property-detail.aspx?pid=717", and have the aspx file add the necessary zeros in front of the pid before it goes off to fetch the data. There has to be some code to sanitize that input anyway (or at least I hope so), so it could be easily added in that section.

Chad Birch
Yeah, I think you're right -- I'm just going to do it in the code as that's the best place for it. Thanks!
A: 

There's no telling what might be in some random regex implementation, but at least with real regular expressions, no.

Charlie Martin
A: 

You haven't explained what general-purpose language you're calling the regex from. However most languages provide the facility to use regexes to match and replace text. Match the numeric portion of the string and then use the features of your language to pad the number out with leading zeros.

pmarflee
+2  A: 

If you want to use mod_rewrite, there is a way to do that:

RewriteCond %{QUERY_STRING} ^(([^&]*&)*)num=(\d+)(.*)
RewriteCond 0000%3 ^0+(\d{5})$
RewriteRule ^/reservations/inn_details\.asp$ /reservations/property-detail.aspx?pid=%1 [L,R=301]
Gumbo
+1 for use of a novel regex engine!
Codebrain
A: 

[?&]num=(\d+) will get the value for you. But regexes do not implement logic, only pattern recognition. Your language or toolset needs to provide a way to analyze and deal with it it.

For example in perl, you might:

s/([?&])num=(\d+)/sprintf( "%spid=%5.5d", $1, $2 )/e;

But that of course just addresses just one of your transformation issues.

Axeman