Pattern Matching

  • 14 years ago

    Hi All,
    I have a very large string. It currently has no html formatting.

    I would like to know how I could write a function which would loop through the string, when it found:
    http://www.example.com (or any fully qualified url) it would rewrite it as
    <a href="http://www.example.com">http://www.example.com</a>

    Also if it could do the same for mail addresses that would be great. I am using VB.Net as my language of choice.

    Regards
    Materialised

  • 14 years ago

    Hi there,

    Imports System.Text.RegularExpressions
    
    Partial Class Signin
        Inherits System.Web.UI.Page
    
        Dim source As String = "sdvsdfvsdfhfhggfdgb http://www.mysite.com sdfdf fhgrthwradfedsfg sfcsdf [email protected] adfdf"
    
        Private Function ParseUrl(ByVal d As String) As String
            Dim mc As MatchCollection = Regex.Matches(source, "http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase)
            For Each m As Match In mc
                d = d.Replace(m.Value, String.Format("<a href=""{0}"">{0}</a>", m.Value))
            Next
            Return d
        End Function
    
        Private Function ParseMail(ByVal d As String) As String
            Dim mc As MatchCollection = Regex.Matches(source, "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase)
            For Each m As Match In mc
                d = d.Replace(m.Value, String.Format("<a href=""mailto:{0}"">{0}</a>", m.Value))
            Next
            Return d
        End Function
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            source = ParseUrl(source)
            source = ParseMail(source)
            Response.Write(source)
        End Sub
    
    End Class
     I hope this helps

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Engineers are all basically high-functioning autistics who have no idea how normal people do stuff.” - Cory Doctorow