Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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!
like image 829
Padawan Avatar asked May 15 '26 20:05

Padawan


1 Answers

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

like image 91
The fourth bird Avatar answered May 18 '26 09:05

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!