Srinath Sri
Srinath Sri

Reputation: 1

Regular Expression to Validate if it is not a Decimal or Integer Number

I am trying to find a regular expression to find out the number which is not entered as proper decimal or integer number in a input box

Examples

  1. 1.. - Catch // consecutive Repeating dots
  2. ABC - Catch // All Alphabets
  3. 1.1.1- Catch // dots repeating in a number
  4. !,@,#- Catch // All Special Characters

My current below allow me to catch all examples except example -3 where decimal dots can be repeated in any combination.

void T1_HTextChanged(object sender, EventArgs e)        
{
    if (System.Text.RegularExpressions.Regex.IsMatch(T1_H.Text, "[^0-9.-]+|[.]{2}"))            
    {

        MessageBox.Show("Please enter only numbers.");
        T1_H.Text="";
    }
}

Upvotes: 0

Views: 1538

Answers (3)

Anu Viswan
Anu Viswan

Reputation: 18155

If you want to achieve this with Regular expression, you can use.

^(\d*\.)?\d+$

Demo

But please be aware that you can use Decimal.TryParse as well. You can read more on Decimal.TryParse here

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 8312

Try this regex:

^[0-9]+([.][0-9]{1,2})?$

Explanation:

  • ^ asserts position at start of a line
  • Match a single character present in the list below [0-9]+
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) 0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
  • 1st Capturing Group ([.][0-9]{1,2})?
  • ? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
  • Match a single character present in the list below [.] . matches the character . literally (case sensitive)
  • Match a single character present in the list below [0-9]{1,2} {1,2} Quantifier — Matches between 1 and 2 times, as many times as possible, giving back as needed (greedy)
  • 0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
  • $ asserts position at the end of a line

Working example: https://regex101.com/r/iRaRPX/1/

It will check for all integers and decimal numbers up to two decimal points. You can change that according to your requirement.

Upvotes: 1

Francois
Francois

Reputation: 3080

If you really want to use a regexp you can use: ^[0-9]+(\.[0-9]+)?$.

You can test it here https://regex101.com/r/UB6eRT/1

If you want to know if it's a valid number you can also try to convert it and check if you get an error.

Upvotes: 1

Related Questions