-3

I am trying to extract a number/word 84900 from the below string ,the keywords are HEIGHT & CM.

String s ="I am with weight 600 KG AND HEIGHT 84900 CM";

Also : If I want to extract multiple words from a string what cane be done.Say for eg2 :ITEM ORDERED AT 2030 IS 5620 POUNDS, I need to extract ORDERED , 2030,5620

Please give me a solution with java regular expression. Thanks

V.R.Manivannan
  • 21
  • 2
  • 10
  • There are lots of answers already but I think you need to give a couple examples of the data if you want one that's useful to you. With just the one example it's impossible to make a really useful pattern. – Casey Dec 12 '13 at 18:16
  • M21B8's answer is currently selected as the correct answer. It is incorrect and does not work. So as to not confuse people who may stumble onto this question in the future, it should be unselected as the correct answer. – axiopisty Dec 12 '13 at 18:47

3 Answers3

0

You can use [0-9]+ for finding the one or more number.

    String  k ="I am with weight 600 KG AND HEIGHT 84900 CM";
    Pattern p = Pattern.compile("[0-9]+");
    Matcher m = p.matcher(k);
    while(m.find()){
        System.out.println(m.group());
    }

OUTPUT

600
84900

EDIT:

For that you need to change the regex as (?<=HEIGHT )[0-9]+(?= CM)

enter image description here

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
0

HEIGHT\s([0-9]*)\sCM

would do it - but it's very specific

Edit. didn't see it was java use + instead of *

VisualBean
  • 4,908
  • 2
  • 28
  • 57
0

To understand how to do this you should really read the documentation for regular expressions in the Java API - particularly at the section "Special constructs (named-capturing and non-capturing)". Any examples here are going to be very specific to the use case you specified but not generally applicable. So this question is not useful for other people who may stumble upon it. But here is an SSCCE that will give you the answer for this specific use case.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * http://stackoverflow.com/questions/20550821/regular-expression-for-getting-number-between-two-words
 */
public class Main {
    public static void main(String[] args) {
        String testString = "I am with weight 600 KG AND HEIGHT 84900 CM";
        Pattern pattern = Pattern.compile("(?<=HEIGHT)\\s*([0-9]+)\\s*(?=CM)");
        Matcher matcher = pattern.matcher(testString);
        while(matcher.find()){
            System.out.println("Height: '" + matcher.group(1) + "'");
        }
    }
}
axiopisty
  • 4,972
  • 8
  • 44
  • 73