Try
String regex = "[0-9]+";
or
String regex = "\\d+";
As per Java regular expressions, the + means "one or more times" and \d means "a digit".
Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d
References:
Java Regular Expressions
Java Character Escape Sequences
Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.
Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
Question 1:
Isn't it necessary to add
^and$to the regex, so it won't match "aa123bb" ?
No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.
Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:
Difference between matches() and find() in Java Regex
Question 2:
Won't this regex also match the empty string,
""?*
No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.
Question 3
Isn't it faster to compile a regex Pattern?
Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
Answer from vikingsteve on Stack OverflowShould I validate numbers using regex or Java types?
What if a user enters commas in numbers?
Can I validate both integers and decimals together?
Try
String regex = "[0-9]+";
or
String regex = "\\d+";
As per Java regular expressions, the + means "one or more times" and \d means "a digit".
Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d
References:
Java Regular Expressions
Java Character Escape Sequences
Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.
Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
Question 1:
Isn't it necessary to add
^and$to the regex, so it won't match "aa123bb" ?
No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.
Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:
Difference between matches() and find() in Java Regex
Question 2:
Won't this regex also match the empty string,
""?*
No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.
Question 3
Isn't it faster to compile a regex Pattern?
Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
You can also use NumberUtil.isNumber(String str) from Apache Commons
Use this regex to select only numbers that aren't connected to any text
\b\d+\b
\d+allows any number of digits\bat the start and the end defines a word boundary so that it doesn't match words liketext12,9gag,4chanetc
Demo: https://regex101.com/r/Fzm2PS/2
// Will match 12, 34,
// Will not match text12, string, 9gag
What you want is a "positive look-behind" construct in your REGEX.
"[0-9]+(?<=[a-zA-Z])"
Matches:
the 9 in "a9";
the 10 in "B10";
the 9 in "a9A"
Doesn't Match:
the 9 in "9A";
the 10 in "+10"
the 10 in " 10"
You're using a Java flavor regex. The correct regex pattern would be:
^(?!26)([-()]*\d){5}[-()]*$
This one will make it so your input cannot start with 26. However, your post did not specify if it could be something like --2)6-218 (it doesn't start with 26, however the first two digits are 26. If this were the case, then you would need:
^(?![-()]*2[-()]*6)([-()]*\d){5}[-()]*$
The 10 character max should be validated on the input, maxlength=10.
Edit: as @zx81 pointed out, I had a few unnecessary escapes. I don't know what I was thinking, sorry. However, this regex pattern does not accept empty strings.
This regex will do what you want (see demo):
^(?!\D*(?:26|555))(?=(?:\D*\d){5}\D*$)[\d()-]{5,10}$
If you no longer want to reject 555, you can go with:
^(?!\D*26)(?=(?:\D*\d){5}\D*$)[\d()-]{5,10}$
And if 2--6123 is not allowed, change the regex to
^(?!\D*2[()-]*6)(?=(?:\D*\d){5}\D*$)[\d()-]{5,10}$
Explain Regex
^ # the beginning of the string
(?! # look ahead to see if there is not:
\D* # non-digits (all but 0-9) (0 or more
# times (matching the most amount
# possible))
(?: # group, but do not capture:
26 # '26'
| # OR
555 # '555'
) # end of grouping
) # end of look-ahead
(?= # look ahead to see if there is:
(?: # group, but do not capture (5 times):
\D* # non-digits (all but 0-9) (0 or more
# times (matching the most amount
# possible))
\d # digits (0-9)
){5} # end of grouping
\D* # non-digits (all but 0-9) (0 or more
# times (matching the most amount
# possible))
$ # before an optional \n, and the end of
# the string
) # end of look-ahead
[\d()-]{5,10} # any character of: digits (0-9), '(', ')',
# '-' (between 5 and 10 times (matching the
# most amount possible))
$ # before an optional \n, and the end of the
# string
Full example:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
Since you're looking for the first number, you can use such regexp:
^\D+(\d+).*
and m.group(1) will return you the first number. Note that signed numbers can contain a minus sign:
^\D+(-?\d+).*
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex1 {
public static void main(String[]args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("hello1234goodboy789very2345");
while(m.find()) {
System.out.println(m.group());
}
}
}
Output:
1234
789
2345