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

Padawan :

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!
The fourth bird :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122865&siteId=1