尝试构建正则表达式来检查模式 [英] Trying to build a regular expression to check pattern

查看:47
本文介绍了尝试构建正则表达式来检查模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a) 以数字开头和结尾
b) 连字符应以数字开头和结尾
c) 逗号应该以数字开头和结尾
d) 数字范围应为 1-31

a) Start and end with a number
b) Hyphen should start and end with a number
c) Comma should start and end with a number
d) Range of number should be from 1-31


e) 如果数字以连字符 (-) 开头,则不能以逗号以外的任何其他字符结尾,并遵循上面列出的所有规则.
例如.2-2,1 OR 2,2-1 有效而 1-1-1-1 无效

例如
a) 1-5,5,15-29
b) 1,28,1-31,15
c) 15,25,3
d) 1-24,5-6,2-9


e) If a number starts with a hyphen (-), it cannot end with any other character other than a comma AND follow all rules listed above.
E.g. 2-2,1 OR 2,2-1 is valid while 1-1-1-1 is not valid

E.g.
a) 1-5,5,15-29
b) 1,28,1-31,15
c) 15,25,3
d) 1-24,5-6,2-9

试过这个,但即使字符串以逗号开头也能通过:

Tried this but it passes even if the string starts with a comma:

/^[0-9]*(?:-[0-9]+)*(?:,[0-9]+)*$/

推荐答案

这个怎么样?这将至少检查规则 a、b 和 c,但不检查规则 d.

How about this? This will check rules a, b and c, at least, but does not check rule d.

/^[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*$/

如果您需要确保所有数字都在 1-31 范围内,那么表达式会变得更丑:

If you need to ensure that all the numbers are in the range 1-31, then the expression will get a whole lot uglier:

<代码>/^([1-9]|[12][0-9]|3[01])(-([1-9]|[12][0-9]|3[01]]))?(,([1-9]|[12][0-9]|3[01])(-([1-9]|[12][0-9]|3[01]))?)*$/

请注意,您的示例 c 包含一个不属于 1-31 范围内的数字 56,因此它不会通过第二个表达式.

Note that your example c contains a number, 56, that does not fall within the range 1-31, so it will not pass the second expression.

这篇关于尝试构建正则表达式来检查模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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