how to check string contains numeric value in java using regex

In this post we will learn how to check string contains numeric value using regex (regular expression) in java.

Regular expressions provides one of the simplest ways to find whether string contains numeric value or not in java.

Example >
string 'java7' contains numeric value
string 'java@&8' contains numeric value
string '123' contains numeric value


string 'java' doesn't contains numeric value
string 'java@&' doesn't contains numeric value


Example 1 to check string contains numeric value in java using regex >
regex (Regular Expression) used = ".*\\d.*"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringContainsNumericExample1 {
public static void main(String[] args) {
     Pattern pattern = Pattern.compile(".*\\d.*");
     String str = "java7";
     Matcher matcher = pattern.matcher(str);
     if (matcher.matches()) {
          System.out.println("string '"+str + "' contains numeric value");
     } else {
          System.out.println("string '"+str + "' doesn't contains numeric value");
     }
}
}
/*
string 'java7' contains numeric value
*/



Example 2 to check string contains numeric value in java using regex >
regex (Regular Expression) used = "[a-zA-Z ]*\\d+.*"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringContainsNumericExample2 {
public static void main(String[] args) {
     Pattern pattern = Pattern.compile("[a-zA-Z ]*\\d+.*");
     String str = "java7";
     Matcher matcher = pattern.matcher(str);
     if (matcher.matches()) {
          System.out.println("string '"+str + "' contains numeric value");
     } else {
          System.out.println("string '"+str + "' doesn't contains numeric value");
     }
}
}
/*
string 'java7' contains numeric value
*/




Example - to check string contains numeric value, where passed string doesn’t contain any numeric value (i.e string doesn’t contain any numeric digit) >
regex (Regular Expression) used = ".*\\d.*"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringContainsNumericExample {
public static void main(String[] args) {
     Pattern pattern = Pattern.compile(".*\\d.*");
     String str = "java";
     Matcher matcher = pattern.matcher(str);
     if (matcher.matches()) {
          System.out.println("string '"+str + "' contains numeric value");
     } else {
          System.out.println("string '"+str + "' doesn't contains numeric value");
     }
}
}
/*
string 'java' doesn't contains numeric value
*/


No comments:

Post a Comment