Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get substring with regular expression

Tags:

java

regex

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.

like image 571
StefanE Avatar asked Aug 19 '10 14:08

StefanE


2 Answers

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
}
like image 148
KeatsPeeks Avatar answered Oct 18 '22 00:10

KeatsPeeks


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])};
like image 36
Andreas Dolk Avatar answered Oct 17 '22 23:10

Andreas Dolk