6

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 (that is, 132 and 194) into two variables. Otherwise the string is static with only numbers changing.

0

3 Answers 3

10

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a million for the help, saved my (very stressed) day here!
I would rather use this pattern .*?([0-9]+)/([0-9]+).*. No unnecessary characters.
4

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

1 Comment

+1 - You are always better off using multiple .split() calls with simpler regexes than using one .split() call with even moderately complex regexes.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.