views:

745

answers:

2

I've been working on this RegEx for the past day or so and I think I have it worked out so that it returns the data I want. First a little background.

I have a content editor that users will be able to edit web pages. They can format text, add links, etc.. standard content editor stuff. When they click save, the editor provides the ability to get the content (editor.Content) and put it into a string. What I want to do is get any links (<a> tags) and find out if they are internal or external links and if they are PDF files.

Here is the Expression I've come up with:

<a\b[^<>]*href\s*=\s*[\""\'](?<domain>https?:\/\/[^\/\s\'\""]*)*\/?(?<path>\/?[^\s\""]+?)?[[>\""\']

With this, I am able to separate the domain (if it has one) and the path out. Then, I loop through the matches...

dim matchColl as MatchCollection = Regex.Matches(editorContent, regExString)
For Each m as Match in matchColl
   If m.Groups("domain").value <> myInternalDomain and m.Groups("domain").value <> "" then
       'this is an external domain... do some stuff
   End If
   If m.Groups("path").value.EndsWith(".pdf") then
         'it is a pdf, do some other stuff...
   End if
Next

My question is this... the parts where I 'do some stuff' to the values, what would be the best way to get that back into my 'editorContent' string? I could probably put the editorContent into a StringBuilder and do a whole bunch of replaces on it, but is that very efficient?

So, for example, with the PDF, I want to specify that it open in a new window (target="_blank") and for the external URL, add some javascript code into the onclick attribute.

Any ideas would be great!

Thanks!

+2  A: 

I think you want do a Regex.Replace and pass in a MatchEvaluator. Basically the MatchEvaluator is a delegate to a function that returns a replacement string.

Andrew Hare
That worked perfectly! I boggles my mind how powerful RegEx's are... this is great!
hacker
A: 

Dear all! i am baffled, I get back a match collection from a matches search off of a regex obect. how do I replace all instances of a given keyword in those matchcollection and then have it be bolded? seems like a very easy problem but i can figure it out please please help me its urgent

thank you

shyma
You should ask this as a top-level question, not an answer to this one.
Craig Walker