Check and Extract a Number from a String in Java

Extract digits from string - StringUtils Java

Use this code numberOnly will contain your desired output.

   String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");

Extract digits from a string in Java

You can use regex and delete non-digits.

str = str.replaceAll("\\D+","");

Check and extract a number from a String in 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. :)

How to extract numbers from a string and get an array of ints?

Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}

... prints -2 and 12.


-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \ as \\ in a Java String though. So, \d+ matches 1 or more digits.

how to extract numeric values from input string in java

String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
matcher.find();
System.out.println(matcher.group());
}

Extract number from a String

Regex can be used like this :

public static void main(String args[]) {
String text1 = "ID 6 IDENTIFICATION NUMBER 600026821 NAME: BECK POSTCODE 60025";
System.out.println(text1.replaceAll(".*?\\b(6000\\d+)\\b.*", "$1")); // replace everything except a number that starts with 6 and is followed by 000 with "".

}

O/P :

600026821

Note : You can use (6000\\d{5}) instead of (6000\\d+) if you are certain that the number of digits will be 9.

Extract only number from a string

You can use Regex to solve the problem

public static List<Integer> extractNumbers(String s){       
List<Integer> numbers = new ArrayList<Integer>();

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);

while(m.find()){
numbers.add(Integer.parseInt(m.group()));
}
return numbers;
}

Extract numbers from String and add them

Why don't you use split like this:

String[] myValues = stString.split(" ");

And after that get the values by myValues[1] and myValues[2]



Related Topics



Leave a reply



Submit