Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 921
Geos Avatar asked Dec 22 '22 05:12

Geos


2 Answers

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);
                }
        }
}
like image 89
Hans W Avatar answered Jan 12 '23 01:01

Hans W


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();
like image 44
Frank Krueger Avatar answered Jan 12 '23 00:01

Frank Krueger