2017-06-22 47 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希望這可以幫助你:) –