开发者

Get substring with regular expression

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.


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
}


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜