简体   繁体   中英

Regular expression to check if string contains only zeros

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.

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.

^(?=.*?[1-9])\d+(\.\d+)?$

您可以为此使用简单的lookahead ,这将验证是否至少有一个[1-9]

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]+$'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM