2010-08-19 98 views
6

我被正则表达式和Java卡住了。获取正则表达式的子字符串

我输入的字符串,看起来像这样:

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

我想读出的第一和第二值(即132194)分为两个变量。否则,字符串是静态的,只有数字发生变化。

回答

10

我假设“第一个值”是132,第二个是194

这应该做的伎俩:

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 
} 
+0

万分感谢您的帮助,救了我的(非常强调)这里的一天! – StefanE 2010-08-19 14:57:29

+0

我宁愿使用这种模式'。*?([0-9] +)/([0-9] +)。*'。没有不必要的字符 – 2010-08-19 15:02:52

4

你可以用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" 
} 

或作为一个班轮:

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

int[] result = new int[]{Integer.parseInt(values[0]), 
         Integer.parseInt(values[1])}; 
+0

+1 - 与使用一个.split()调用,即使是适度复杂的正则表达式相比,使用更简单的正则表达式可以更好地使用多个.split()调用。 – whaley 2010-08-19 15:18:44

1

如果你是68和94后,这里将工作模式:

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