views:

103

answers:

4

Hello

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

+3  A: 

Java has regular expressions:

Pattern p = Pattern.compile("this is (.+?) example with (\\d+) songs");
Matcher m = p.matcher("this is a good example with 234 songs");
boolean b = m.matches();
Frank Krueger
+5  A: 

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);
                }
        }
}
Hans W
+1  A: 

if second string is a pattern. you can compile it into regexp, like a

String in = "this is a good example with 234 songs";
String pattern = "this is %%type%% example with %%number%% songs";
Pattern p = Pattern.compile(pattern.replaceAll("%%(\w+)%%", "(\\w+)");
Matcher m = p.matcher(in);
if (m.matches()) {
   for (int i = 0; i < m.groupsCount(); i++) {
      System.out.println(m.group(i+1))
   }
}

If you need named groups you can also parse your string pattern and store mapping between group index and name into some Map

splix
He wants spaces included, \w won't work
Frank Krueger
A: 

Geos, I'd recommend using the Apache Velocity library http://velocity.apache.org/. It's a templating engine for strings. You're example would look like

this is a good example with 234 songs
this is $type example with $number songs

The code to do this would look like

final Map<String,Object> data = new HashMap<String,Object>();
data.put("type","a good");
data.put("number",234);

final VelocityContext ctx = new VelocityContext(data);

final StringWriter writer = new StringWriter();
engine.evaluate(ctx, writer, "Example templating", "this is $type example with $number songs");

writer.toString();
Ceilingfish
I think he is trying to do "the opposite" of templating. I.e. given the output string and the template extract the context that generated the output.
flybywire