Java Regex多组匹配&提取 [英] Java Regex multiple groups match & extract

查看:233
本文介绍了Java Regex多组匹配&提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一句话:

"Hello my name is Neo and my company brand name is Company Country1. But we have also other companies like Company Country2 (in Europe), and also Company Country3 (in Asia)".

我想在匹配器中只对所有公司ContryX进行exctract / parse

I would like to exctract/parse in matcher only all Company ContryX.

你知道如何在正则表达式中匹配某些指定句子的所有出现(并得到那些)吗?

Do you know how to match in regex all occurences (and get those) of some specified sentence?

推荐答案

使用 Matcher.find

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

public class App {

    public static void main(String[] args) throws IOException {

        String s = "Hello my name is Neo and my company brand name is Company Country1. "
                + "But we have also other companies like Company Country2 (in Europe), "
                + "and also Company Country3 (in Asia)";

        Pattern pattern = Pattern.compile("Company Country\\d");
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()) {
            String group = matcher.group();
            System.out.println(group);
        }
    }
}

输出:

Company Country1
Company Country2
Company Country3

这篇关于Java Regex多组匹配&提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆