Geos
Geos

Reputation: 1467

string parsing in java

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

Upvotes: 4

Views: 957

Answers (4)

Ceilingfish
Ceilingfish

Reputation: 5455

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();

Upvotes: 0

Frank Krueger
Frank Krueger

Reputation: 71053

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();

Upvotes: 3

Igor Artamonov
Igor Artamonov

Reputation: 35951

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

Upvotes: 1

Hans W
Hans W

Reputation: 3891

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);
                }
        }
}

Upvotes: 7

Related Questions