java 使用正则表达式获取子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3522928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:14:25  来源:igfitidea点击:

Get substring with regular expression

javaregex

提问by StefanE

I'm stuck with regular expression and Java.

我坚持使用正则表达式和 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, 132and 194) into two variables. Otherwise the string is static with only numbers changing.

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

回答by KeatsPeeks

I assume the "first value" is 132, and the second one 194.

我假设“第一个值”是 132 ,第二个是 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
}

回答by Andreas Dolk

You can solve it with String.split():

您可以使用以下方法解决它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])};

回答by stark

If you were after 68 and 94, here's a pattern that will work:

如果你在 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);
    }