从给定地址Java正则表达式中提取域名

从给定地址Java正则表达式中提取域名,java,regex,pattern-matching,Java,Regex,Pattern Matching,我想要输出“xyz”而不是“www.xyz.com”。 我问这个主要是因为我想知道除了模式本身之外,如何在模式之间提取一些东西 public class Test { public static void main(String[] args) { Pattern p = Pattern.compile("www[.].+[.]com"); Matcher m = p.matcher("www.xyz.com"); if(m.find())

我想要输出“xyz”而不是“www.xyz.com”。 我问这个主要是因为我想知道除了模式本身之外,如何在模式之间提取一些东西

public class Test {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("www[.].+[.]com");
        Matcher m = p.matcher("www.xyz.com");
        if(m.find()){
            System.out.println(m.group());
        }
        in.close();
    }
}
您可以使用
\.(.*?)
这表示两点之间的任何东西:

Pattern p = Pattern.compile("www\\.(.*?)\\.com");
Matcher m = p.matcher("I saw a tree. tree was tall. now I will search tree on www.google.com .");
if (m.find()) {
    System.out.println(m.group(1));
}
输出

google
您可以使用
\.(.*?)
这表示两点之间的任何东西:

Pattern p = Pattern.compile("www\\.(.*?)\\.com");
Matcher m = p.matcher("I saw a tree. tree was tall. now I will search tree on www.google.com .");
if (m.find()) {
    System.out.println(m.group(1));
}
输出

google

我不明白你的意思!在我的例子中,我必须使用一个段落作为输入。使用这个可能会引起麻烦。假设输入:“我看到一棵树。树很高。现在我将在www.google.com上搜索这棵树。”@YCF_Lcheck my edit@YashBhutoria希望这能帮助你:)第一组是什么意思?(这意味着第二次匹配吗?)这在较大的段落中有效吗?@Yashbutoria这意味着
www\\.
\\\.com之间的分组是的,我可以在较大的段落中工作,就像您在示例中使用的那样
我看到了一棵树。这棵树很高。现在我将在www.google.com上搜索这棵树。
我不明白你的意思@yashbutoria!在我的例子中,我必须使用一个段落作为输入。使用这个可能会引起麻烦。假设输入:“我看到一棵树。树很高。现在我将在www.google.com上搜索这棵树。”@YCF_Lcheck my edit@YashBhutoria希望这能帮助你:)第一组是什么意思?(这意味着第二次匹配吗?)这在较大的段落中有效吗?@Yashbutoria这意味着
www\\.
\\\.com之间的分组是的,我可以在较大的段落中工作,就像您在示例中使用的那样
我看到了一棵树。这棵树很高。现在我将在www.google.com上搜索这棵树。
问题也不错。如果你达到15个代表,你想练习向上投票,我很乐意帮助你;-)问题也很好。如果你达到15个代表,你想练习向上投票,我很乐意帮助你;-)