How do I write the correct Regex for a url on a page without anchors?
I want to strip all urls as ( http: // .... ) And replace them with anchors <a></a>
, but my requirement is: Don't touch anchors and page definition (Doc type) like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
So I need to find a plain text with a url ...
I am trying to override my render page internally and I made a BrowserAdapter:
<browser refID="default">
<controlAdapters>
<adapter controlType="System.Web.Mvc.ViewPage"
adapterType="Facad.Adapters.AnchorAdapter" />
</controlAdapters>
</browser>
it looks like this:
public class AnchorAdapter : PageAdapter
{
protected override void Render(HtmlTextWriter writer)
{
/* Get page output into string */
var sb = new StringBuilder();
TextWriter tw = new StringWriter(sb);
var htw = new HtmlTextWriter(tw);
// Render into my writer
base.Render(htw);
string page = sb.ToString();
//regular expression
Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
//get the first match
Match match = regx.Match(page);
//loop through matches
while (match.Success)
{
//output the match info
System.Web.HttpContext.Current.Response.Write("<p>url match: " + match.Groups[0].Value+"</p>");
//get next match
match = match.NextMatch();
}
writer.Write(page);
}
}
a source to share
You just have to search a little ahead and behind the url to see if there are quotes, hardly anyone is inserting the quoted url as plaintext, but urls are always quoted in tags and dotypes. So your regex becomes:
(^|[^'"])(http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?)([^'"]+|$)
(^ | [^ '"] +) means the beginning of a line or a character that is NOT a quote ([^'"] | $) means the end of a line or not a quote
The extra parentheses around the old regex will ensure it's a capturing group so you can get the actual URL with \ 2 (group 2) instead of getting extra crap it could match around the edges of the URL
By the way, your url looks pretty bad, there are more compact and precise forms. You really don't have to run EVERYTHING.
a source to share