字符串的一部分必须是 0-100 之间的数字的正则表达式 [英] Regular expression where part of string must be number between 0-100

查看:29
本文介绍了字符串的一部分必须是 0-100 之间的数字的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证序列号.为此,我们在 C# 中使用正则表达式,并且在某个产品中,序列号的一部分是自午夜以来的秒数".一天有 86400 秒,但是如何验证它是这个字符串中的 5 位数字呢?:

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

我不能用这个概念:

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

因为那时 86399 将无效.我该如何克服呢?我想要类似的东西:

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.

推荐答案

生成正则表达式以匹配任意数值范围http://utilitymill.com/utility/Regex_For_Range

产生以下正则表达式:

0*([0-9]{1,4}|[1-7][0-9]{4}|8[0-5][0-9]{3}|86[0-3][0-9]{2}|86400)

输出说明:

First, break into equal length ranges:
  0 - 9
  10 - 99
  100 - 999
  1000 - 9999
  10000 - 86400

Second, break into ranges that yield simple regexes:
  0 - 9
  10 - 99
  100 - 999
  1000 - 9999
  10000 - 79999
  80000 - 85999
  86000 - 86399
  86400 - 86400

Turn each range into a regex:
  [0-9]
  [1-9][0-9]
  [1-9][0-9]{2}
  [1-9][0-9]{3}
  [1-7][0-9]{4}
  8[0-5][0-9]{3}
  86[0-3][0-9]{2}
  86400

Collapse adjacent powers of 10:
  [0-9]{1,4}
  [1-7][0-9]{4}
  8[0-5][0-9]{3}
  86[0-3][0-9]{2}
  86400

Combining the regexes above yields:
  0*([0-9]{1,4}|[1-7][0-9]{4}|8[0-5][0-9]{3}|86[0-3][0-9]{2}|86400)

在这里测试:http://osteele.com/tools/rework/

这篇关于字符串的一部分必须是 0-100 之间的数字的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆