Example: Replace /2/215.html with &id2=2&id3=215
So here is a function to look for this pattern and replace with this other pattern:
static string ReplacePattern(Match m) { var x = m.ToString(); Console.WriteLine("Match is : " + x); var c = x.Count(f => f == '/'); // Or equivalent: x.Split('/').Length - 1; var slashIdx = x.IndexOf('/'); for (int i = 0; i < c; i++) { var newPatt = string.Format("&id{0}=", (i + 2).ToString()); x = slashIdx > 0 ? x.Substring(0, slashIdx) + newPatt + x.Substring(slashIdx + 1) : newPatt + x.Substring(slashIdx + 1); slashIdx = x.IndexOf('/', slashIdx + 1); } x = x.Replace(".html", string.Empty); Console.WriteLine("Replaced is: " + x); return x; }
And here is a quick tester function:
private static void TestReplacePattern() { string s = @"<loc>http://www.blabla.com/index.php?id=0/123/23/1/456/5.html"; Regex r = new Regex("/[0-9/]+.html"); Console.WriteLine(r.Replace(s, new MatchEvaluator(ReplacePattern))); }
No comments:
Post a Comment