逗号分隔的数字正则表达式 [英] Comma Separated Numbers Regex

查看:113
本文介绍了逗号分隔的数字正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证数字 1-8 的逗号分隔列表.

I am trying to validate a comma separated list for numbers 1-8.

2,4,6,8,1 是有效输入.

我尝试了 [0-8,]* 但它似乎接受 1234 为有效.它不需要逗号,它让我输入一个大于 8 的数字.我不知道为什么.

I tried [0-8,]* but it seems to accept 1234 as valid. It is not requiring a comma and it is letting me type in a number larger than 8. I am not sure why.

推荐答案

[0-8,]* 将匹配 0 的零个或多个连续实例>8,,在您的字符串中的任何位置.你想要更像这样的东西:

[0-8,]* will match zero or more consecutive instances of 0 through 8 or ,, anywhere in your string. You want something more like this:

^[1-8](,[1-8])*$

^ 匹配字符串的开头,而 $ 匹配结尾,确保您正在检查整个字符串.它将匹配单个数字,加上零个或多个逗号实例,后跟一个数字.

^ matches the start of the string, and $ matches the end, ensuring that you're examining the entire string. It will match a single digit, plus zero or more instances of a comma followed by a digit after it.

这篇关于逗号分隔的数字正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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