用于检查字符串是否仅包含零的正则表达式

Regular expression to check if string contains only zeros
2020-10-18
•  译文(汉语)
•  原文(英语)

-我很好奇,乘法在哪里出现?当然要得到0,您本来应该有0?

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

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

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.

Talk1:
Why don't you just convert the string to a number and check if it is 0?
Talk2:
I presume you are going to need to use the amount afterwards anyway so checking if the number is 0 would be a much better solution.
Talk3:
Try parsing the string. If parse is successful, multiply it with some number, if you get zero it has zeroes only. Simplest solution ;)
Talk4:
- I'm curious, where does the multiplication come into it? Surely to get 0, you would have had a 0 to begin with?
Talk5:
In the sense of 'because we can', you could do it without parsing or regex, by checking if any char is between 1 and 9 `bool hasnumbers = inputstring.Any(c => c >= '1' && c <= '9');`
Solutions1

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.

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

You can use a simple `lookahead` for this which will validate if there is at least one `[1-9]`.

Solutions3

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

Talk1:
Talk2:
I'm not OP but I'd like to say a late thanks, I didn't even think of this. Helped me a lot.