java中的模式匹配:从字符串文字中提取数字

时间:2014-09-19 10:02:02

标签: java regex

我想从字符串中提取2个数字。 我的示例代码是:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static int returnInt(String pattern, String inputString) {
        Pattern intPattern = Pattern.compile(pattern);
        Matcher matcher = intPattern.matcher(inputString);
        matcher.find();
        String input = matcher.group(0);
        return Integer.parseInt(input);
    }

    public static void main(String[] args) {
        System.out
                .println(returnInt(
                        "\\d+",
                        "The following DTE jobs have been submitted to ServerFarm for execution. (farm showjobs -d -j 12774076) can be used to monitor job status. The output format is JobID : TopoName : TopoAlias : JobStatus. ( The initial job status is listed in brackets. If job status is FAILED, then the job can not be run at all! Otherwise please check job status periodically. ) :21554030 : IDM_INSTALLER_1H1N_REL11 : IDM_INSTALLER_1H1N_REL11 : WAITING (Being queueed on server farm)"));
    }
}

我希望输出为:12774076和21554030,但输出仅为12774076 请帮助!!

1 个答案:

答案 0 :(得分:2)

循环matcher.find()并返回List<Integer>,因为可以有多于1个匹配 例如。

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static List<Integer> returnInt(String pattern, String inputString) {
        Pattern intPattern = Pattern.compile(pattern);
        Matcher matcher = intPattern.matcher(inputString);
        List<Integer> output = new ArrayList<>();
        while (matcher.find()) {
            output.add(Integer.parseInt(matcher.group(0)));
        }

        return output;
    }

    public static void main(String[] args) {
        System.out
                .println(returnInt(
                        "\\d{5,}",
                        "The following DTE jobs have been submitted to ServerFarm for execution. (farm showjobs -d -j 12774076) can be used to monitor job status. The output format is JobID : TopoName : TopoAlias : JobStatus. ( The initial job status is listed in brackets. If job status is FAILED, then the job can not be run at all! Otherwise please check job status periodically. ) :21554030 : IDM_INSTALLER_1H1N_REL11 : IDM_INSTALLER_1H1N_REL11 : WAITING (Being queueed on server farm)"));
    }
}

输出

[12774076, 21554030]