Reputation: 105
I need some help with regex in Java.
We have string, and I want that String.matches give me "true" if our string contains N
digits.
For example(N = 12
):
+012345678900 - true
0123-4567-0000 - true;
but:
+0123456789 - false
0123-4567-000000 - false.
I tried this one (.*[0-9].*){N}
and this one ^(.*[0-9].*){N}$
. But it was incorrectly.
Upvotes: 4
Views: 327
Reputation: 174696
You may try this,
^(?:\\D*\\d){12}\\D*$
matches
method won't need anchors, so
(?:\\D*\\d){12}\\D*
would be enough..
\\D
matches any character but not of digit. So (?:\\D*\\d){12}
ensures that there must be any no of non-dgit chars but it must contain exactly 12 digits. Last \\D*
matches zero or more non-digit characters.
Upvotes: 5