Simple regex expression - how to reshape url

I want to take a url that looks like this:

http://www.example.com/activated-alumina-desiccant/t101c5.aspx

      

And change it to this:

http://www.example.com/Default.aspx?t=101&c=5

      

I also need flexibility to add other query variables like:

http://www.example.com/activated-alumina-desiccant/t101c5p232.aspx

      

which could get me:

http://www.example.com/Default.aspx?t=101&c=5&p=232

      

So far I have the beginning of what I need [^/]+$

Which gives me back the last part of the url, but other than that, how do I split the last bit and individual querystring variables? I'm stumped!

This is where the regex will continue: enter image description here

+3


source to share


3 answers


This regex will split the URL with three query variables:

([^/]+//+[^/]+/)[^/]+/(\w)?(\d+)?(\w)?(\d+)?(\w)?(\d+)?\.aspx

Use this to replace a string:

"$1Default.aspx?$2=$3&$4=$5&$6=$7"



EDIT:

If trailing &=

, for example, http://www.example.com/Default.aspx?t=101&=&=

does not cause a problem, you can get away with a single regex configured to convert the maximum number of pending variables. This maximum is limited by how many capture groups are allowed with the regex engine in the replacement string (9 capture groups give an absolute maximum of 4, 99 gives an absolute maximum of 49).

If trailing &=

is a problem, you need to enter a regex for each expected number of pending number variables. With this in mind, the regex should be slightly modified (example with two queries):

regex: ([^/]+//+[^/]+/)[^/]+/(\w)(\d+)(\w)(\d+)\.aspx


replacement:"$1Default.aspx?$2=$3&$4=$5"

+3


source


Note: starting code C #.

Ideone Demo

  string s="t101c5p2";
  string[]arr= Regex.Split(s,"(?<=[0-9])(?=[a-zA-Z])");
  foreach(String str in arr)
  {
    string replaceStr = new Regex("([a-z])([0-9])").Replace(str,"$1=$2");
    Console.WriteLine(replaceStr);
  }

      



Output:

t=101
c=5
p=2

      

0


source


string url = "http://www.example.com/activated-alumina/t101c5p232.aspx";
var segment = new Uri(url).Segments.Last();
var parameters = 
      String.Join("&", Regex.Matches(segment, @"([a-zA-Z]+)(\d+)")
                            .OfType<Match>()
                            .Select(m => m.Groups[1] + "=" + m.Groups[2]));

string result = "http://www.example.com/Default.aspx?" + parameters;
// http://www.example.com/Default.aspx?t=101&c=5&p=232

      

DEMO

0


source







All Articles