2017-06-22 49 views
1

我想输出“xyz”而不是“www.xyz.com”。 主要是我问这个,因为我想知道如何提取模式之间的某些内容,除了模式本身。从给定地址提取域名Java正则表达式

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(); 
    } 
} 
+0

有趣的问题了。如果你达到15代表,你想练习upvoting,我很高兴帮助;-) – GhostCat

回答

0

您CA使用\.(.*?)\.这意味着这两个点之间的任何事情:

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 
+0

我不明白你@YashBhutoria! –

+0

在我的情况下,我必须使用段落作为输入。使用这可能会造成麻烦。 假设这个输入:“我看到一棵树,树很高,现在我将在www.google.com上搜索树。” @YCF_L –

+0

检查我的编辑@YashBhutoria希望这可以帮助你:) –