string parsing in java

java, parsing, string

Solution

You can do it with regular expressions:

import java.util.regex.*;

class A {
        public static void main(String[] args) {
                String s = "this is a good example with 234 songs";


                Pattern p = Pattern.compile("this is a (.*?) example with (\\d+) songs");
                Matcher m = p.matcher(s);
                if (m.matches()) {
                        String kind = m.group(1);
                        String nbr = m.group(2);

                        System.out.println("kind: " + kind + " nbr: " + nbr);
                }
        }
}

Problem

What is the best way to do the following in Java. I have two input strings ``` this is a good example with 234 songs this is %%type%% example with %%number%% songs ``` I need to extract type and number from the string. Answer in this case is type="a good" and number="234" Thanks

Original source