在正则表达式匹配后找到第一个单词

时间:2013-08-09 03:04:53

标签: java regex

如何在比赛结束后抓住第一个单词?

例如,我找到Car后,如何抓取Chevy

public class NewExtractDemo {
    public static void main(String[] args) {
        String input = "I have the following Car: Chevy, Truck: Ford, Van: Honda";

        Pattern p = Pattern.compile("(Car|Truck|Van)");
        Matcher m = p.matcher(input);

        List<String> Search = new ArrayList<String>();
        while (m.find()) {
            System.out.println("Found a " + m.group() + ".");
            Search.add(m.group());
        }
    }
}

2 个答案:

答案 0 :(得分:14)

使用capturing groups

(Car|Truck|Van):\s*(\w+)

现在.group(1)将返回Car.group(2)将返回Chevy


String input = "I have the following Car: Chevy, Truck: Ford, Van: Honda";

Pattern p = Pattern.compile("(Car|Truck|Van):\\s*(\\w+)");
Matcher m = p.matcher(input);

while (m.find()) {
    System.out.println(m.group(1) + "\t" + m.group(2));
}
Car     Chevy
Truck   Ford
Van     Honda

答案 1 :(得分:0)

考虑使用常量来避免每次重新编译正则表达式。

/* The regex pattern that you need: (?<=(Car|Truck|Van): )(\w+) */
private static final REGEX_PATTERN = 
                                 Pattern.compile("(?<=(Car|Truck|Van): )(\\w+)");

public static void main(String[] args) {
    String input = "I have the following Car: Chevy, Truck: Ford, Van: Honda";
    Matcher matcher = REGEX_PATTERN.matcher(input);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

输出:

Chevy
Ford
Honda