Check if string contains number in java

Java Regular Expression to Check If String contains at least One Digit

This week’s task is to write a regular expression in Java to check if a String contains any digit or not. For example, passing «abcd» to pattern should false , while passing «abcd1» to return true , because it contains at least one digit. Similarly passing «1234» should return true because it contains more than one digit. Though java.lang.String class provides a couple of methods with inbuilt support of regular expression like split method, replaceAll(), and matches method, which can be used for this purpose, but they have a drawback. They create a new regular expression pattern object, every time you call. Since most of the time we can just reuse the pattern, we don’t need to spend time on creating and compiling patterns, which is expensive compared to testing a String against the pattern.

For reusable patterns, you can take the help of java.util.regex package, it provides two class Pattern and Matcher to create pattern and check String against that pattern.

Читайте также:  Ввод значения переменной python

In order to complete this, we first need to create a regular expression pattern object, we can do that by passing regular expression String «(.)*(\\d)(.)*» to Pattern.compile() method, this returns a compiled version of regular expression String. By using this pattern you can get Matcher object to see if the input string passes this regular expression pattern or not.

We will learn more about our regular expression String in the next section when we will see our code example to check if String contains a number or not.

Regular Expression to Find if String contains Number or Not

The following code sample is our complete Java program to check if String contains any number or not. You can copy this code into your favorite IDE like Eclipse, Netbeans, or IntelliJ IDEA. Just create a Java source file with the name of our public class RegularExpressionDemo and run it from IDE itself.

Alternatively, you can run the Java program from the command line by first compiling a Java source file using the javac compiler and then running it using the java command.

Now let’s understand the core of the program, the regular expression itself. We are using «(.)*(\\d)(.)*» , where dot and start are meta characters used for any character and any number of timer. \d is a character class for matching digits, and since backward slash needs to escaped in Java, we have put another backslash e.g. \\d ..

So if you read this regular expression, it days any character any number of time, followed by any digit then again any character any number of time. This means this will match any String which contains any numeric digit e.g. from 0 — 9.

Читайте также:  Линейная классификация python пример

Regular Expression in Java for Checking if String contains Number

import java.util.Scanner ;

Источник

Java — check if string contains any numbers

Kourtney-White

In this article, we would like to show you how to check if a string contains any numbers in Java.

Practical example

In this example, we use a regular expression (regex) with Pattern.matcher() to check if the strings contain any numbers.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example < public static void main(String[] args) < String text = "ab123cd"; String regex = ".*\\d.*"; // regex to check if string contains any numbers Pattern pattern = Pattern.compile(regex); // compiles the regex // find match between given string and pattern Matcher matcherText = pattern.matcher(text); // return true if the string matched the regex Boolean textMatches = matcherText.matches(); System.out.println(textMatches); // true >>

2. Using Character.isDigit()

In this example, we create a function that loops through the string and checks if any character is a digit with Character.isDigit(char ch) method.

public class Example < public static void main(String[] args) < String letters = "ABCD"; String numbers = "1234"; String mixed = "a12b"; System.out.println(containsNumbers(letters)); // false System.out.println(containsNumbers(numbers)); // true System.out.println(containsNumbers(mixed)); // true >public static boolean containsNumbers(String string) < if (string == null || string.isEmpty()) < return false; >for (int i = 0; i < string.length(); ++i) < if (Character.isDigit(string.charAt(i))) < return true; >> return false; > >

Источник

Check if String contains number example

This Java example shows how to check if a string contains number using the Double class, regular expression, and apache commons library.

How to check if a string contains a number in Java?

1) Check if a string contains a number using the Double wrapper class

Use the parseDouble method of the Double wrapper class to check. If the string does not contain a number, the parseDobule method throws NumberFormatException exception which you can catch to do further processing.

2) Using Apache Commons Library

If you are using the Apache Commons library, you can use the isNumber static method of the NumberUtils class to check if the string contains a valid number as given below.

This method returns true if the string contains a valid number, false otherwise.

Note: As you may have observed, the isNumber method returns false for “+12.32” value. Use this approach only if you do not expect such string in the input values.

3) Using a regular expression

You can also use a regular expression to check if the string contains a valid number or not as given below.

The “\\d” pattern denotes a digit in regular expression. Our pattern “\\d+” means “one or more digits”. You can also use the “6+” pattern instead of the “\\d+”.

This pattern does not work for anything except for positive integers (and that too without the “+” sign). Use this only if it fits the requirements.

Let’s create a bit more accommodative pattern to include floating point and negative numbers.

Our original pattern was “\\d+” which checked only for one or more digits. Now we are going to include the minus sign “-” which should be optional, as well as the optional dot “.” for floating point numbers. Here is the updated regular expression pattern.

Источник

Java — check if string only contains numbers

Lia-Perez

In this article, we would like to show you how to check if the string only contains numbers in Java.

1. Using regex

In this example, we use a regular expression (regex) with Pattern.matcher() to check if the strings contain only numbers.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example < public static void main(String[] args) < String numbers = "1234"; String text = "ABC"; String regex = "^1+$"; // regex to check if string contains only digits Pattern pattern = Pattern.compile(regex); // compiles the regex // find match between given string and pattern Matcher matcherNumbers = pattern.matcher(numbers); Matcher matcherText = pattern.matcher(text); // return true if the string matched the regex Boolean numbersMatches = matcherNumbers.matches(); Boolean textMatches = matcherText.matches(); System.out.println(numbersMatches); // true System.out.println(textMatches); // false >>

2. Using Character.isDigit()

In this example, we create a function that loops through the string and checks if each character is a digit with Character.isDigit(char ch) method.

public class Example < public static void main(String[] args) < String numbers = "1234"; String text = "ABC"; System.out.println(onlyNumbers(numbers)); // true System.out.println(onlyNumbers(text)); // false >public static boolean onlyNumbers(String string) < if (string == null || string.isEmpty()) < return false; >for (int i = 0; i < string.length(); ++i) < if (!Character.isDigit(string.charAt(i))) < return false; >> return true; > >

Источник

Оцените статью