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

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());
        }
    }
}
2个回答

16

使用捕获组

(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));
}
汽车     雪佛兰
卡车     福特
货车     本田

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接