Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to check if string contains only zeros

Tags:

c#

regex

I need to validate an Amount field, which should not be Zero amount. For eg. it CANNOT be 0000,0.00,000.000,0 BUT it CAN be 0.0001, 1.000,1.00,1234.00 etc values.

Tried @"[^1-9]+" and @"0+((\.0+)" But they invalidate every value which contains a zero.

like image 966
mukulsharma1146 Avatar asked Jun 11 '15 06:06

mukulsharma1146


People also ask

How do you check if a string contains only zeros?

Try parsing the string. If parse is successful, multiply it with some number, if you get zero it has zeroes only.

How to check if string contains digits?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.

How to check string contains only numeric values?

Check if String Contains Only Numbers using isdigit() method Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It returns “False”.

How to check if all the characters in a string are digits Java?

Java – Check if String contains only Digits To check if String contains only digits in Java, call matches() method on the string object and pass the regular expression "[0-9]+" that matches only if the characters in the given string are digits.


2 Answers

I don´t see why you need a regex, simply convert the string to a number and check if that is 0:

decimal actNumber;
if(decimal.TryParse(myAmount, out actNumber) && actNumber > 0) 
{ /* ... */ }

Thus you can also use the actual number afterwards.

like image 182
MakePeaceGreatAgain Avatar answered Sep 21 '22 00:09

MakePeaceGreatAgain


If you want a regular expression to check for strings containing only one character, you can just specify that the character be located at the beginning, end, and everywhere in between. Here is an example of how to do so for the digit 0:

regexp '^0+$'

If you are worried about the value containing non-zero digits, you can ensure that no such characters are present using:

regexp '^[^1-9]+$'

like image 41
Grant Langseth Avatar answered Sep 18 '22 00:09

Grant Langseth