Regular expression question.

Hello all,

I have the following scenario:

Retrieve data from third party via a WebClient object, and load retrieved content into a StringBuilder object.

From there, I want to replace all matches with my own version:

Given the following string "<a href=""v ghjgh="">link</a><a href="">link</a><a href="">link</a>"

I want to look for the following pattern "<a href="(\S*?)""

And replace all matches with "<a href="http://www.x.asp?page=$1""

In practice, this works, and returns "<a href="http://www.x.asp?page="v ghjgh="">link</a><a href="http://www.x.asp?page=">link</a><a href="http://www.x.asp?page=">link</a>"

However, I must also have the matched pattern ($1) replaced as a URLEncoded string, otherwise the above result will work properly.

I don't know the MatchEvaluator, but wondered if this might be the place to add my own function for this purpose? Or is there a nice little Regexp function that I can enclose my $1 match with?

Thanks for your help.
Who is Participating?
joechinaConnect With a Mentor Commented:
static void Main(string[] args)
            string s = "<a href=\"\"v ghjgh=\"\">link</a><a href=\"\">link</a><a href=\"\">link</a>";
            MatchEvaluator me = new MatchEvaluator(ReplaceFunc);
            string result = Regex.Replace(s, "(?<=href=\")(?<link>[^\"]*)", me);
        static string ReplaceFunc(Match m)
            return "http://www.x.asp?page=" + HttpUtility.UrlEncode(m.Groups["link"].Value);
AlfaNoMoreAuthor Commented:
Thanks joechina, simple as that eh? :-)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.