Reputation: 13471
I want to create a regular expresion where I want match in case my number are separated by a coma. For example:
1 OK
1,2,3 OK
1\n2,3 OK
1,\n Not OK
1,,2 Not OK
1,\n2 Not Ok
So far I create this expresion
\d+(([,.|\n])+\d+)*
If I change the last * to be at least 1 with +
\d+(([,.|\n])+\d+)+
Then all previous scenarios works but not this one
1 Not OK//And should be ok
I´m using matcher.find()
Matcher matcher = Pattern.compile(pattern).matcher(number);
if (matcher.find()) {
System.out.println("total number:" + matcher.group(0));;
}
Any idea what I´m doing wrong in my regex?
Upvotes: 1
Views: 56
Reputation: 785631
You can use this regex:
^\d+(?:(?:,|\n)\d+)*$
Java regex:
Pattern p = Pattern.compile("^\\d+(?:(?:,|\\n)\\d+)*$");
PS: To match literal \n
you will need:
^\d+(?:(?:,|\\n)\d+)*$
Upvotes: 1