I need a regular expression that validate price in the format like:
0.07 //valid
0.0 //Invalid
20 //valid
All the above Expressions are that which I want to achieve
^\d{0,8}(\.\d{1,4})?$
I use the above Expression which also accepts 0.0 which is invalid in my case. Thank you.
为什么不使用那个RegEx,但是也检查value > 0
我认为你也不想要负价 - 其他'数字检查'方法最有可能被认为是有效的
You could use a negative lookahead that asserts that what follows from the start of the line is not zero or times a zero followed by an optional part that matches a dot and only zeroes.
^(?!0*\\.0+$)\\d*(?:\\.\\d+)?$
Explanation
^
Assert the start of the line (?!
Negative lookahead
0*\\.0+$
Match zero or more times a 0 followed by a dot and one or more times a 0 until the end of the string )
Close lookahead \\d*
Match zero or more times a digit (?:
Non capturing group
\\.\\d+
Match a dot followed by one or more digits )?
Close non capturing group and make it optional $
Assert the end of the line In C#, I would advice to use standard libraries to validate decimal values, like using Decimal.TryParse .
You may then implement something like:
public static bool IsValid(string price) {
var result = Decimal.TryParse(price, out decimal d);
if (result && d != 0) {
return true;
}
return false;
}
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.