Check and extract a number from a String in Java

JavaRegexString

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

try this

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

Solution 2 - Java

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.

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - 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. :)

Solution 9 - Java

Try the following pattern:

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

Solution 10 - Java

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

Solution 11 - Java

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";
	}

Solution 12 - Java

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

Solution 13 - Java

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

Solution 14 - Java

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.

Solution 15 - Java

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

Solution 16 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDuaneView Question on Stackoverflow
Solution 1 - JavaEvgeniy DorofeevView Answer on Stackoverflow
Solution 2 - JavaSajal DuttaView Answer on Stackoverflow
Solution 3 - JavaMelih AltıntaşView Answer on Stackoverflow
Solution 4 - JavaMallikarjuna SangisettyView Answer on Stackoverflow
Solution 5 - JavaNarendraView Answer on Stackoverflow
Solution 6 - JavaIshaanView Answer on Stackoverflow
Solution 7 - JavaRaceBaseView Answer on Stackoverflow
Solution 8 - JavaDuaneView Answer on Stackoverflow
Solution 9 - JavaKonstantin YovkovView Answer on Stackoverflow
Solution 10 - Javaabhinav kumarView Answer on Stackoverflow
Solution 11 - Javaeyad davidView Answer on Stackoverflow
Solution 12 - JavaMostafa Arian NejadView Answer on Stackoverflow
Solution 13 - JavaRuchira Gayan RanaweeraView Answer on Stackoverflow
Solution 14 - JavaThorsten KettnerView Answer on Stackoverflow
Solution 15 - JavaRickyrasView Answer on Stackoverflow
Solution 16 - JavaBrad YuanView Answer on Stackoverflow