SgDotNet
Singapore Professional .NET User Group -For Cool Developers

Code snippet - 0008

This post has 3 Replies | 1 Follower

Top 50 Contributor
Posts 82
ericwsw Posted: 04-22-2005 8:45 AM

       Filter out unwanted characters in the string

      
        Dim a, b As String
        a = "123 % Hello $ 456 world 789 $"

        ' b = "123 Hello 456 world 789"
        b = System.Text.RegularExpressions.Regex.Replace(a, "[^\w\s]", "").Trim
        b = System.Text.RegularExpressions.Regex.Replace(b, "\s+", " ")


        ' b = "12345678"
        b = System.Text.RegularExpressions.Regex.Replace(a, "[^\d]", "")
        b = System.Text.RegularExpressions.Regex.Replace(b, "\s+", " ")


        ' b = "Hello world"
        b = System.Text.RegularExpressions.Regex.Replace(a, "[^A-Za-z ]", "").Trim
        b = System.Text.RegularExpressions.Regex.Replace(b, "\s+", " ")


 

Top 10 Contributor
Posts 2,284
Many people do not understand Regular Expressions so you may want to comment just what you code is doing.

The melody of logic will always play out the truth. ~ Narumi Ayumu, Spiral

Top 50 Contributor
Posts 82
Thank you for the feedback Smile [:)]
Top 50 Contributor
Posts 82

The expression \w includes all letters and numbers, the \s all spaces. The ^ negates the expression, so all invalid characters get replaced with an empty string.

The expression  \d  includes all decimal digit. The ^ negates the expression, so all invalid decimal digit get replaced with an empty string.

The expression  \s+  includes one or more spaces, so regardless one or more spaces get replaced with a space

 

Page 1 of 1 (4 items) | RSS
Copyright SgDotNet 2004-2008
Powered by Community Server (Commercial Edition), by Telligent Systems