I am trying to write a regex for java that will match the following string:
number,number,number (it could be this simple or it could have a variable number of numbers, but each number has to have a comma after it there will not be any white space though)
here was my attempt:
[[0-9],[0-9]]+
but it seems to match anything with a number in it
You could try something along the lines of ([0-9]+,)*[0-9]+
This will match:
7
7,52
7,52,999
This will not match:
7, 52
7, 52,
I think this would work
\d+,(\d+,)+
Note that as you want, that will only capture number followed by a comma
I guess you are starting with a String. Why don't you just use String.split(",")
?
^ means the start of a string and $ means the end. If you don't use those, you could match something in the middle ( b
matched "abc").
The +
works on the element before it. b
is an element, [0-9]
is an element, and so are groups (things wrapped in parenthesis).
So, the regex you want matches:
^
[0-9]
(,[0-9])+
$
or, ^[0-9](,[0-9])+$
Try regex as [\\d,]*
string representation as [\\\\d,]*
eg below:
Pattern p4 = Pattern.compile("[\\d,]*");
Matcher m4 = p4.matcher("12,1212,1212ad,v");
System.out.println(m4.find()); //prints true
System.out.println(m4.group());//prints 12,1212,1212
If you want to match minimum one comma (,) and two numbers eg 12,1212
then you may want to use regex as (\\d+,)+\\d+
with string representation as \\\\d+,)+\\\\d+
. This regex matches aa region with a number minimum one digit followed by one comma(,) followed by minimum one digit number.
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.