How to Check If a String Is Numeric in Java

How to check if a String is numeric in Java

With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)

Java String - See if a string contains only numbers and not letters

If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){

to:

if (text.matches("[0-9]+") && text.length() > 2) {

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).

Check and extract a number from a String in Java

The solution I went with looks like this:

Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);

Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);

if (matcher1.find() && matcher2.find())
{
int number = Integer.parseInt(matcher1.group());
pw.println(number + " squared = " + (number * number));
}

I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)

How to check if a string contains only digits in Java

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());

How to check if a String is numeric in Java

With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)

Determine if a String is an Integer in Java

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix)) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt(radix);
return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}

How do I check if a String contains a numeric value

Try this:

    for(int character=0; character<roomNo.length(); character++){
if(!Character.isDigit(roomNo.charAt(character))) {
return false;
}
}
return true;

Or as others have said, use regular expressions

Check if a string contains only digits and white space in java Android

As @ADM suggested in comment you can update your regex [0-9]+ with below

[0-9 ]+

so it look like

 String Cardresult = edtCashCard.getText().toString();
if (Cardresult.matches("[0-9 ]+")){
Toast.makeText(getApplicationContext(), "Good Job the strings are numbers", Toast.LENGTH_SHORT).show();

}
else{
Toast.makeText(getApplicationContext(), "Error the string contains character", Toast.LENGTH_SHORT).show();
}


Related Topics



Leave a reply



Submit