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.
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.
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.