简体   繁体   中英

Java: Regular expression for the input field only numbers and commas + space characters

There is a field that is filled with numbers or groups of numbers.

After the comma must be a space!

The symbol " , " and the space cannot be the beginning and / or at the end of the field

^[\d+]{1,}([,]{1}[\s]{1}).*[\d+]$ 
- this does not work. please help to write a regular expression according to the described condition.

example

1 - ok!
2, 3 - ok!
6, 7, 4 -ok!
,5 - bad!
5 6 0 - bad!
4,5 - bad!

You could use a repeating group with a space (or \\s ) prepended.

In your pattern you could remove the .* and match the last \\d+ inside the group. Then repeat the group 0+ times.

It would look like ^[\\d]{1,}([,]{1}[\\s]{1}[\\d]+)*$

Note that you don't have to put the \\d+ between square brackets or else the + would be matched literally and the quantifier {1} could be omitted:

^\d+(?:, \d+)*$

In Java

String regex = "^\\d+(?:, \\d+)*$";

Regex demo | Java demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM