3

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

例如,一旦我找到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());
        }
    }
}
4

2 回答 2

16

使用捕获组

(汽车|卡车|货车):\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));
}
汽车雪佛兰
卡车福特
范本田
于 2013-08-09T03:06:57.743 回答
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
于 2013-08-09T03:40:55.487 回答