We help IT Professionals succeed at work.

c# Regular Expression

Hi,
I'm trying to replace some broken links in a database and need help with the following:

Broken URL:
<a title="" href="http://mywebsite.com/399">Music In June 2005</a>

I want to change it to:
<a title="" href="http://mywebsite.com/Search.php?ContentID=399">Music In June 2005</a>

I need to do this in c#.  

Thanks
Comment
Watch Question

Terry WoodsIT Guru
Most Valuable Expert 2011

Commented:
Match with regular expression:
href="http://mywebsite[.]com/(\d+)"
And replace with:
href="http://mywebsite.com/Search.php?ContentID=$1"

You'll need to escape the double quotes, and ensure you use a global replace option.

Commented:
Try this, in C#:
resultString = Regex.Replace(subjectString, @"http://mywebsite\.com/(.*?)>", "http://mywebsite.com/Search.php?ContentID=$1>");

Open in new window


HTH,
Dan
IT Guru
Most Valuable Expert 2011
Commented:
Slight to Dan's solution, in case it matches more than it should with the .* pattern in the match:
resultString = Regex.Replace(subjectString, @"http://mywebsite\.com/(\d+)>", "http://mywebsite.com/Search.php?ContentID=$1>");

Open in new window

Commented:
If you use digits (I wanted to allow the possibility for a alphanumeric ID), then you'll have to match the " too:
resultString = Regex.Replace(subjectString, @"http://mywebsite\.com/(\d+"")>", "http://mywebsite.com/Search.php?ContentID=$1>");

Open in new window

Most Valuable Expert 2011
Top Expert 2015

Commented:
...and ensure you use a global replace option.
Unnecessary, as all replaces in C# are global (well, unless you use a particular version of the Replace method, but we're not here!)    = )

Author

Commented:
Hi,
I will test these solutions asap.
Thanks

Commented:
So...
You accepted a non-working solution, and gave it a B rating. Why?