繁体   English   中英

在与正则表达式匹配的字符串中找到一些文本

[英]Find some text in a string on matching to a reg-ex

我正在寻找形式的句子。 文本文档的每一行的第三字段中的“ .... X在Y ...上受教育”。 X是已知的,Y是未知的。 成功匹配后,如何获得Y的值? 以下是我的代码:

    Pattern p1 = Pattern.compile(".* educated at .*");
    int count = 0;

    while((line = br.readLine()) != null){
        String datavalue[] = line.split("\t");
        String text = datavalue[2];
        Matcher m = p1.matcher(text);
        if(m.matches()){
            count++;
            //System.out.println(text);
            //How do I get Y?

        }
    }

我是reg-ex的新手。 任何帮助表示赞赏。

将找到的文本捕获为一组:

Pattern p1 = Pattern.compile(".* educated at (.*)");//note the parenthesis
int count = 0;

while((line = br.readLine()) != null){
    String datavalue[] = line.split("\t");
    String text = datavalue[2];
    Matcher m = p1.matcher(text);
    if(m.matches()){
        count++;
        System.out.println(m.group(1));

    }
}

请参阅https://docs.oracle.com/javase/tutorial/essential/regex/groups.html了解更多信息

您可以一行完成:

while((line = br.readLine()) != null){
    String y = line.replaceAll(".*?\t.*?\t{^\t]*educated at (\\w+).*|.*", "$1");

如果没有匹配项,则变量y将为空白。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM