正则表达式逗号分隔数 [英] Regex for Comma Separated Number

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

问题描述

我想验证用户输入,它只是逗号分隔的数字。我想用正则表达式做到这一点,但不能拿出正确的EX pression。

这应该验证以下字符串(及以上):

  1
12
123
1,234
12345
123456
 

和无效以下字符串(和疯狂):

  1,1
1,12
12,1
12,12
123,1
123,1
 

任何帮助将是很大的AP preciated。

下面就是我试过到目前为止(编辑:不工作),另外还有几个变种 - >

  ^(((\ d {1,3},)* \ D {3})|(\ d {1,3}))$
^(\ D {1,3} [,])* \ D {3} | \ d {1,3} $
 

解决方案

这个怎么样:

  ^ \ D {1,3}([,] \ D {3})* $
 

基本上,你可以有1-3位逗号免费。在此之后,你需要一个逗号。如果你有一个逗号,它的必须的后跟3多个数字。该逗号3位序列可以出现任意次数。

编辑:作为安德鲁野兔观察到的,你不来代替放置<$关心的是在括号中发现超出的事实,它匹配的,这样你就可以使用非捕获组C $ C>:开盘后括号:

  ^ \ D {1,3}(?:[,] \ D {3})* $
 

I'm trying to validate user input, which is just comma separated numbers. I'd like to do this with RegEx, but can't come up with the right expression.

It should validate the following strings (and larger):

1
12
123
1,234
12,345
123,456

and invalidate the following strings (and crazier):

1,1
1,12
12,1
12,12
123,1
123,1

Any help would be greatly appreciated.

Here's what I've tried so far (EDIT: which don't work), along with several variants ->

^(((\d{1,3},)*\d{3})|(\d{1,3}))$
^(\d{1,3}[,])*\d{3}|\d{1,3}$

解决方案

How about this:

^\d{1,3}([,]\d{3})*$

Basically you can have 1-3 digits comma free. After that, you need a comma. If you've got a comma, it must be followed by 3 more digits. That comma-3-digit sequence can appear any number of times.

EDIT: As Andrew Hare observed, you don't care about what was found inside the parentheses beyond the fact that it matched, so you can use a non-capturing group instead by placing ?: after the opening parenthesis:

^\d{1,3}(?:[,]\d{3})*$

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

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