1

I have got a String for example.

"Quantity : 2.85 kg"

Here I only need to extract the number with exact configuration 2.85.

String.replaceAll("[^0-9]",""); only extracts number as 285, but I need 2.85.

Kindly help.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57

2 Answers2

1

You must be kidding guys, the pattern for a digit is

p = "/d*(./d+)?"

and extract it is :

 Matcher m = Pattern.compile(p)
while(m.find()) 
res = m.group(0)
user8426627
  • 903
  • 1
  • 9
  • 19
  • No it is not. Your pattern actually does not work. You have to escape the d with a backslash, you have to escape the dot to match it literally and because everything is optional it would also match an empty string. – The fourth bird May 21 '19 at 18:14
  • ok its then "((//d*([.]//d+) | //d+)" , forgot that in java you cant control how greedy * is. Other patterns are worse in this answer – user8426627 May 21 '19 at 18:22
  • I am afraid that is also not correct. `((//d*([.]//d+) | //d+)` is missing a parenthesis, you have to use a backslash instead of a forward slash. With those corrections these are the matches which I think is not what OP is meaning to match. https://regex101.com/r/x2akHU/1 – The fourth bird May 21 '19 at 18:33
1

Regex is any character, then one or more digits with a dot and following two digits, space and kg. A capturing group is used to capture the part thas is to be extracted.

String test = "Quantity : 2.85 kg";

Pattern pattern = Pattern.compile(".*(\\d+\\.\\d\\d) kg");
Matcher matcher = pattern.matcher(test);

if(matcher.matches()){
    System.out.println(matcher.group(1));
}else{
    System.out.println("no match");
}
Juan
  • 5,525
  • 2
  • 15
  • 26