tags:

views:

54

answers:

3

Hi,

I'm stuck with regular expression and Java..

My input string that looks like this:

"EC: 132/194 => 68% SC: 55/58 => 94% L: 625"

I want to read out the first and second values into two variables. Otherwise the string is static with only numbers changing.

Update: By first and second value I mean 132 and 194. Sorry for being unclear.

Very thankful for some help here!

+3  A: 

I assume the "first value" is 132, and the second one 194.

This should do the trick:

String str = "EC: 132/194 => 68% SC: 55/58 => 94% L: 625";

Pattern p = Pattern.compile("^EC: ([0-9]+)/([0-9]+).*$");
Matcher m = p.matcher(str);

if (m.matches())
{
    String firstValue = m.group(1); // 132
    String secondValue= m.group(2); // 194
}
Samuel_xL
Thanks a million for the help, saved my (very stressed) day here!
StefanE
I would rather use this pattern `.*?([0-9]+)/([0-9]+).*`. No unnecessary characters.
Colin Hebert
+2  A: 

You can solve it with String.split():

public String[] parse(String line) {
   String[] parts = line.split("\s+");
   // return new String[]{parts[3], parts[7]};  // will return "68%" and "94%"

   return parts[1].split("/"); // will return "132" and "194"
}

or as a one-liner:

String[] values = line.split("\s+")[1].split("/");

and

int[] result = new int[]{Integer.parseInt(values[0]), 
                         Integer.parseInt(values[1])};
Andreas_D
+1 - You are always better off using multiple .split() calls with simpler regexes than using one .split() call with even moderately complex regexes.
whaley
A: 

If you were after 68 and 94, here's a pattern that will work:

    String str = "EC: 132/194 => 68% SC: 55/58 => 94% L: 625";

    Pattern p = Pattern.compile("^EC: [0-9]+/[0-9]+ => ([0-9]+)% SC: [0-9]+/[0-9]+ => ([0-9]+)%.*$");
    Matcher m = p.matcher(str);

    if (m.matches()) {
        String firstValue = m.group(1); // 68
        String secondValue = m.group(2); // 94
        System.out.println("firstValue: " + firstValue);
        System.out.println("secondValue: " + secondValue);
    }
stark