OGeek|极客世界-中国程序员成长平台

标题: c# - Regular expression where part of string must be number between 0-100 [打印本页]

作者: 菜鸟教程小白    时间: 2022-6-1 20:09
标题: c# - Regular expression where part of string must be number between 0-100

I need to validate serial numbers. For this we use regular expressions in C#, and a certain product, part of the serial number is the "seconds since midnight". There are 86400 seconds in a day, but how can I validate it as a 5-digit number in this string?:

654984051-86400-231324

I can't use this concept:

[0-8][0-6][0-4][0-0][0-0]

Because then 86399 wouldn't be valid. How can I overcome this? I want something like:

[00000-86400]

UPDATE
I want to make it clear that I'm aware of - and agree with - the "don't use regular expressions when there's a simpler way" school-of-thought. Jason's answer is exactly how I'd like to do it, however this serial number validation is for all serial numbers that pass through our system - there's currently no custom validation code for these specific ones. In this case I have a good reason for looking for a regex solution.

Of course, if there isn't one, then that makes the case for custom validation for these particular products undeniable, but I wanted to explore this avenue fully before going with a solution that requires code changes.



Best Answer-推荐答案


Don't use regex? If you're struggling to come up with the regex to parse this that says that maybe it's too complex and you should find something simpler. I see absolutely no benefit to using regex here when a simple

int value;
if(!Int32.TryParse(s, out value)) {
    throw new ArgumentException();
}
if(value < 0 || value > 86400) {
    throw new ArgumentOutOfRangeException();
}

will work just fine. It's just so clear and easily maintainable.






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4