VB.NET - RegEx to validate a string to contain only 0-9, comma nad hypen

Asked By D N C on 28-Sep-12 03:54 AM
Hi All,

Please help me to write a Regex to validate string which should contain only whole numbers, comma and hypen.
Eg) 1-5 or 1,5,6

Thanks in advance :)
Hemanth Kumar replied to D N C on 28-Sep-12 05:25 AM
You can do this Using the Programmatically also see this

string number = "15-,6";
       bool flag1, flag2;
 
       for (int i = 0; i < number.Length; i++)
       {
         if (Char.IsNumber(number[i]))
         {
           flag1 = IsWholeNumber(number[i].ToString());
         }
         else
         {
           if (number[i]=='-' | number[i]==',')
           {
             flag2 = true;
           }
         }
 
       }
       if (flag1 && flag2 )
       {
         //Show a Message that Number Contains ',','-' and Whole Number Too
       }


public bool IsWholeNumber(string strNumber)
    {
      System.Text.RegularExpressions.Regex _RegexNotWholePattern
        = new System.Text.RegularExpressions.Regex("[^0-9]");
      return !_RegexNotWholePattern.IsMatch(strNumber);
    }
Hemanth Kumar replied to D N C on 28-Sep-12 05:25 AM
You can do this Using the Programmatically also see this

string number = "15-,6";
       bool flag1, flag2;
 
       for (int i = 0; i < number.Length; i++)
       {
         if (Char.IsNumber(number[i]))
         {
           flag1 = IsWholeNumber(number[i].ToString());
         }
         else
         {
           if (number[i]=='-' | number[i]==',')
           {
             flag2 = true;
           }
         }
 
       }
       if (flag1 && flag2 )
       {
         //Show a Message that Number Contains ',','-' and Whole Number Too
       }


public bool IsWholeNumber(string strNumber)
    {
      System.Text.RegularExpressions.Regex _RegexNotWholePattern
        = new System.Text.RegularExpressions.Regex("[^0-9]");
      return !_RegexNotWholePattern.IsMatch(strNumber);
    }
Goniey N (Mr. G) replied to D N C on 28-Sep-12 09:28 AM
Use below Code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

      Dim myRegex As New Regex("[0-9,-]")

      If myRegex.IsMatch(TextBox1.Text) Then

        'Write Your Code Here....

        MessageBox.Show("Match")

      End If

End Sub


i had checked it at my side and it works perfectly...

Hope this will helpful to you...