[java] Check if a String contains numbers Java

I'm writing a program where the user enters a String in the following format:

"What is the square of 10?"
  1. I need to check that there is a number in the String
  2. and then extract just the number.
  3. If i use .contains("\\d+") or .contains("[0-9]+"), the program can't find a number in the String, no matter what the input is, but .matches("\\d+")will only work when there is only numbers.

What can I use as a solution for finding and extracting?

This question is related to java regex string

The answer is


As I was redirected here searching for a method to find digits in string in Kotlin language, I'll leave my findings here for other folks wanting a solution specific to Kotlin.

Finding out if a string contains digit:

val hasDigits = sampleString.any { it.isDigit() }

Finding out if a string contains only digits:

val hasOnlyDigits = sampleString.all { it.isDigit() }

Extract digits from string:

val onlyNumberString = sampleString.filter { it.isDigit() }

If you want to extract the first number out of the input string, you can do-

public static String extractNumber(final String str) {                
    
    if(str == null || str.isEmpty()) return "";
    
    StringBuilder sb = new StringBuilder();
    boolean found = false;
    for(char c : str.toCharArray()){
        if(Character.isDigit(c)){
            sb.append(c);
            found = true;
        } else if(found){
            // If we already found a digit before and this char is not a digit, stop looping
            break;                
        }
    }
    
    return sb.toString();
}

Examples:

For input "123abc", the method above will return 123.

For "abc1000def", 1000.

For "555abc45", 555.

For "abc", will return an empty string.


.matches(".*\\d+.*") only works for numbers but not other symbols like // or * etc.


I think it is faster than regex .

public final boolean containsDigit(String s) {
    boolean containsDigit = false;

    if (s != null && !s.isEmpty()) {
        for (char c : s.toCharArray()) {
            if (containsDigit = Character.isDigit(c)) {
                break;
            }
        }
    }

    return containsDigit;
}

ASCII is at the start of UNICODE, so you can do something like this:

(x >= 97 && x <= 122) || (x >= 65 && x <= 90) // 97 == 'a' and 65 = 'A'

I'm sure you can figure out the other values...


As you don't only want to look for a number but also extract it, you should write a small function doing that for you. Go letter by letter till you spot a digit. Ah, just found the necessary code for you on stackoverflow: find integer in string. Look at the accepted answer.


Below code snippet will tell whether the String contains digit or not

str.matches(".*\\d.*")
or
str.matches(.*[0-9].*)

For example

String str = "abhinav123";

str.matches(".*\\d.*") or str.matches(.*[0-9].*)  will return true 

str = "abhinav";

str.matches(".*\\d.*") or str.matches(.*[0-9].*)  will return false

Try the following pattern:

.matches("[a-zA-Z ]*\\d+.*")

s=s.replaceAll("[*a-zA-Z]", "") replaces all alphabets

s=s.replaceAll("[*0-9]", "") replaces all numerics

if you do above two replaces you will get all special charactered string

If you want to extract only integers from a String s=s.replaceAll("[^0-9]", "")

If you want to extract only Alphabets from a String s=s.replaceAll("[^a-zA-Z]", "")

Happy coding :)


try this

str.matches(".*\\d.*");

Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);

You can try this

String text = "ddd123.0114cc";
    String numOnly = text.replaceAll("\\p{Alpha}","");
    try {
        double numVal = Double.valueOf(numOnly);
        System.out.println(text +" contains numbers");
    } catch (NumberFormatException e){
        System.out.println(text+" not contains numbers");
    }     

I could not find a single pattern correct. Please follow below guide for a small and sweet solution.

String regex = "(.)*(\\d)(.)*";      
Pattern pattern = Pattern.compile(regex);
String msg = "What is the square of 10?";
boolean containsNumber = pattern.matcher(msg).matches();

The code below is enough for "Check if a String contains numbers in Java"

Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");

if(m.find()){
    System.out.println("Hello "+m.find());
}

public String hasNums(String str) {
        char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        char[] toChar = new char[str.length()];
        for (int i = 0; i < str.length(); i++) {
            toChar[i] = str.charAt(i);
            for (int j = 0; j < nums.length; j++) {
                if (toChar[i] == nums[j]) { return str; }
            }
        }
        return "None";
    }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript