Answered by:
Need help rewriting url

Question
-
I am using UrlRewriting.UrlRewrite and need a reg ex to change the url from http://www.site.com/p~p-86572910~Nikon-CoolPix-S630-Digital-Camera.aspx to http://www.site.com/Nikon-CoolPix-S630-Digital-Camera.aspx.
Regular Expressions are completely new to me. Can anyone help me with the code for this?
Thank you in advance for the help.Sunday, February 14, 2010 2:46 AM
Answers
-
You can get away with a single call to Regex.Replace, provided my assumptions about the format of your URLs are correct.
Try:
string rewrittenUrl = Regex.Replace (originalUrl, @"(?<=/)([A-Za-z0-9\-)+~)+", "");
which means:
(?<=/) = match only if the preceding character is a forward slash...
(...)+ = one or more runs of...
[A-Za-z0-9\-]+~ = a sequence of one or more alphanumeric characters or dashes followed by a tilde (~)
If a match is found, it is replaced with nothing (hence, removed).
In the example above, the string:
p~p-86572910~ satisfies the above conditions.
HTH
--mc- Proposed as answer by IsisTheDamned Tuesday, February 16, 2010 4:14 PM
- Marked as answer by SamAgain Monday, February 22, 2010 9:54 AM
Sunday, February 14, 2010 3:33 AM
All replies
-
You can get away with a single call to Regex.Replace, provided my assumptions about the format of your URLs are correct.
Try:
string rewrittenUrl = Regex.Replace (originalUrl, @"(?<=/)([A-Za-z0-9\-)+~)+", "");
which means:
(?<=/) = match only if the preceding character is a forward slash...
(...)+ = one or more runs of...
[A-Za-z0-9\-]+~ = a sequence of one or more alphanumeric characters or dashes followed by a tilde (~)
If a match is found, it is replaced with nothing (hence, removed).
In the example above, the string:
p~p-86572910~ satisfies the above conditions.
HTH
--mc- Proposed as answer by IsisTheDamned Tuesday, February 16, 2010 4:14 PM
- Marked as answer by SamAgain Monday, February 22, 2010 9:54 AM
Sunday, February 14, 2010 3:33 AM -
Hi, dthardy:
If your URL is right, and the "p~p-86572910~" is what you want to remove. I believe you could use the following code. Assuming that the pattern is "X~X-########~", where X stands for any single letter and #stands for any single digit.
public static String ChangeUrl(String url) { Regex rs = new Regex(@"(?<=/)[a-zA-Z]~[a-zA-Z]-\d{8}~"); string result = rs.Replace(url, ""); return result; }
Good luck.
Please mark the right answer at right time.
Thanks,
SamMonday, February 15, 2010 3:24 AM -
Why not just use the String.Replace .net function? Regex would be overkill for such a simple task.
AdamTuesday, February 16, 2010 6:56 PM -
I want to change it not only for the visitor but for spiders also. Would this work with search engine spiders?Friday, February 19, 2010 12:07 AM