I'm using the below regular expression:
Pattern testPattern= Pattern.compile("^[1-9][0-9]{14}");
Matcher teststring= testPattern.matcher(number);
if(!teststring.matches())
{
error("blah blah!");
}
My requirements are:
Am I missing anything in regex?
With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).
+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
If you want to get only digits using REGEXP, use the following regular expression( ^[0-9]*$) in where clause. Case 1 − If you want only those rows which have exactly 10 digits and all must be only digit, use the below regular expression.
With "^[1-9][0-9]{14}"
you are matching 15
digit number, and not 10-15
digits. {14}
quantifier would match exactly 14
repetition of previous pattern. Give a range there using {m,n}
quantifier:
"[1-9][0-9]{9,14}"
You don't need to use anchors with Matcher#matches()
method. The anchors are implied. Also here you can directly use String#matches()
method:
if(!teststring.matches("[1-9][0-9]{9,14}")) {
// blah! blah! blah!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With