I'm writing a program where the user enters a String in the following format:
"What is the square of 10?" - I need to check that there is a number in the String
- and then extract just the number.
- 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?
116 Answers
try this
str.matches(".*\\d.*"); 4If 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.
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; } 1s=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 :)
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()); } 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(); 2Pattern p = Pattern.compile("(([A-Z].*[0-9])"); Matcher m = p.matcher("TEST 123"); boolean b = m.find(); System.out.println(b); 2The 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. :)
Try the following pattern:
.matches("[a-zA-Z ]*\\d+.*") 3Below 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 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"; } 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() } 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"); } 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.
.matches(".*\\d+.*") only works for numbers but not other symbols like // or * etc.
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...