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.

1
  • You could directly match \d+(\.\d+)? to extract the number Commented May 21, 2019 at 17:26

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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.
ok its then "((//d*([.]//d+) | //d+)" , forgot that in java you cant control how greedy * is. Other patterns are worse in this answer
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. regex101.com/r/x2akHU/1
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");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.