Regex to Check Whether a String Contains Only Numbers

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

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

Regex to check whether a string contains only numbers

var reg = /^\d+$/;

should do it. The original matches anything that consists of exactly one digit.

Check if string contains only digits

how about

let isnum = /^\d+$/.test(val);

how can i tell if a string contains ONLY digits and spaces in python using regex

The basic regular expression would be

/^[0-9 ]+$/

However is works also if your string only contains space. To check there is at least one number you need the following

/^ *[0-9][0-9 ]*$/

You can try it on there

Check if string contains ONLY NUMBERS or ONLY CHARACTERS (R)

you need to persist your regex

all_num <- "123"
all_letters <- "abc"
mixed <- "123abc"

grepl("^[A-Za-z]+$", all_num, perl = T) #will be false
grepl("^[A-Za-z]+$", all_letters, perl = T) #will be true
grepl("^[A-Za-z]+$", mixed, perl=T) #will be false

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 do you check in python whether a string contains only numbers?

You'll want to use the isdigit method on your str object:

if len(isbn) == 10 and isbn.isdigit():

From the isdigit documentation:

str.isdigit()

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

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

Check if string only contains numbers in php

You want to use preg_match in that case as both 61,23311 and 55403.22 are valid numbers (depending on locale).
i.e.

if (preg_match("/^\d+$/", $number)) {
return "is valid"
} else {
return "invalid"
}


Related Topics



Leave a reply



Submit