Reputation: 21393
In Java for String class there is a method called matches, how to use this method to check if my string is having only digits using regular expression. I tried with below examples, but both of them returned me false as result.
String regex = "[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
String regex = "^[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
Upvotes: 182
Views: 671684
Reputation: 34
Refer to org.apache.commons.lang3.StringUtils
public static boolean isNumeric(CharSequence cs) {
if (cs == null || cs.length() == 0) {
return false;
} else {
int sz = cs.length();
for(int i = 0; i < sz; ++i) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
}
Upvotes: 1
Reputation: 187
I would use this regex for integers:
^[-1-9]\d*$
This will also work in other programming languages because it's more specific and doesn't make any assumptions about how different programming languages may interpret or handle regex.
\\d+
As @vikingsteve has pointed out in java, the matches method matches a complete string, not parts of a string. In other words, it is unnecessary to use ^\d+$ (even though it is the official way of regex).
Online regex checkers are more strict and therefore they will behave differently than how Java handles regex.
Upvotes: -1
Reputation: 2391
In Java for String
class, there is a method called matches()
. With help of this method you can validate the regex expression along with your string.
String regex = "^[\\d]{4}$";
String value = "1234";
System.out.println(data.matches(value));
The Explanation for the above regex expression is:-
^
- Indicates the start of the regex expression.
[]
- Inside this you have to describe your own conditions.
\\\d
- Only allows digits. You can use '\\d'or 0-9 inside the bracket both are same.
{4}
- This condition allows exactly 4 digits. You can change the number according to your need.
$
- Indicates the end of the regex expression.
Note: You can remove the
{4}
and specify+
which means one or more times, or*
which means zero or more times, or?
which means once or none.
For more reference please go through this website: https://www.rexegg.com/regex-quickstart.html
Upvotes: 0
Reputation: 40388
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:
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));
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
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.
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());
Upvotes: 420
Reputation: 1
Try this part of code:
void containsOnlyNumbers(String str)
{
try {
Integer num = Integer.valueOf(str);
System.out.println("is a number");
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("is not a number");
}
}
Upvotes: -1
Reputation: 21
According to Oracle's Java Documentation:
private static final Pattern NUMBER_PATTERN = Pattern.compile(
"[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
"([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
"(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
"[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}
Upvotes: 2
Reputation: 231
We can use either Pattern.compile("[0-9]+.[0-9]+")
or Pattern.compile("\\d+.\\d+")
. They have the same meaning.
the pattern [0-9] means digit. The same as '\d'. '+' means it appears more times. '.' for integer or float.
Try following code:
import java.util.regex.Pattern;
public class PatternSample {
public boolean containNumbersOnly(String source){
boolean result = false;
Pattern pattern = Pattern.compile("[0-9]+.[0-9]+"); //correct pattern for both float and integer.
pattern = Pattern.compile("\\d+.\\d+"); //correct pattern for both float and integer.
result = pattern.matcher(source).matches();
if(result){
System.out.println("\"" + source + "\"" + " is a number");
}else
System.out.println("\"" + source + "\"" + " is a String");
return result;
}
public static void main(String[] args){
PatternSample obj = new PatternSample();
obj.containNumbersOnly("123456.a");
obj.containNumbersOnly("123456 ");
obj.containNumbersOnly("123456");
obj.containNumbersOnly("0123456.0");
obj.containNumbersOnly("0123456a.0");
}
}
Output:
"123456.a" is a String
"123456 " is a String
"123456" is a number
"0123456.0" is a number
"0123456a.0" is a String
Upvotes: 2
Reputation: 31555
Using regular expressions is costly in terms of performance. Trying to parse string as a long value is inefficient and unreliable, and may be not what you need.
What I suggest is to simply check if each character is a digit, what can be efficiently done using Java 8 lambda expressions:
boolean isNumeric = someString.chars().allMatch(x -> Character.isDigit(x));
Upvotes: 17
Reputation: 3753
You can also use NumberUtil.isNumber(String str) from Apache Commons
Upvotes: 35
Reputation: 37813
One more solution, that hasn't been posted, yet:
String regex = "\\p{Digit}+"; // uses POSIX character class
Upvotes: 12
Reputation: 47290
Long.parseLong(data)
and catch exception, it handles minus sign.
Although the number of digits is limited this actually creates a variable of the data which can be used, which is, I would imagine, the most common use-case.
Upvotes: 7
Reputation: 5686
You must allow for more than a digit (the +
sign) as in:
String regex = "[0-9]+";
String data = "23343453";
System.out.println(data.matches(regex));
Upvotes: 9