簡體   English   中英

使用正則表達式獲取子字符串

[英]Get substring with regular expression

我堅持使用正則表達式和Java。

我的輸入字符串如下所示:

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

我想將第一個和第二個值(即132194 )讀出為兩個變量。 否則,字符串是靜態的,只有數字改變。

我假設“第一個值”是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
}

您可以使用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])};

如果您分別是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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM