Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

.net - Regex for Comma Separated Number

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}$
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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})*$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...