I have a string like
> 12.4N-m/kg.
From the above string I need to get a value 12.4
.
When I use replace all function str.replaceAll("[^.0-9]", "")
.
This doesn't work when then string has two dots.
The location of float value may differ.
I have a string like
> 12.4N-m/kg.
From the above string I need to get a value 12.4
.
When I use replace all function str.replaceAll("[^.0-9]", "")
.
This doesn't work when then string has two dots.
The location of float value may differ.
First discard all non flot characters and then covert to Float like this:
float f = Float.valueOf("> 12.4N-m/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", ""));
// now f = 12.4
Assuming your input always has a space before the number and an N
after it:
String t = "> 12.4N-m/kg.";
Pattern p = Pattern.compile("^.*\\s(\\d+\\.\\d)N.*$");
Matcher matcher = p.matcher(t);
if (matcher.matches()) {
System.out.println(Float.valueOf(matcher.group(1)));
}
following code will work with assumption that input string always starts with "> "
and it has proper float prefixed.
int i=2;
while(Character.isDigit(str.charAt(i)) || str.charAt(i) == '.')
i++;
float answer = Float.valueOf(str.substring(2,i));
I think the previous answers leave out two points:
Because of the second point I don't think replacing everything that is a non-digit is a good idea. One should rather search for the first number in the string:
Matcher m = p.matcher(str);
System.out.println("Input: "+ str);
if (m.find()) {
System.out.println("Found: "+ m.group());
try {
System.out.println("Number: "+ Float.parseFloat(m.group()));
} catch (Exception exc) {
exc.printStackTrace();
}
}
Alternatively, you could do something like
int i, j;
for (i = 0; i < str.length(); ++i) {
if (mightBePartOfNumber(str.charAt(i))) {
break;
}
}
for (j = i; j < str.length(); ++j) {
if (!mightBePartOfNumber(str.charAt(j))) {
break;
}
}
String substr = str.substring(i, j);
System.out.println("Found: "+ substr);
try {
System.out.println("Number: "+ Float.parseFloat(substr));
} catch (Exception exc) {
exc.printStackTrace();
}
with a helper
private static boolean mightBePartOfNumber(char c) {
return ('0' <= c && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E';
}
I have tried the above options but not worked for me , Please try below pattern
Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?");