2017-04-11 59 views
1

比方說,我們有兩個字符串(ULRs):字符的第N次出現,並且如果條件語句

https://stackoverflow.com/questions/ask
https://web.whatsapp.com/

我需要這樣來寫表達式:

如果第3斜線後

( /)是沒有或第三斜線不存在做

{ 
some operation 
} else { 
another action 
} 

請幫助。

 List<String> list = new ArrayList<String>(); 

     while((str = in.readLine()) != null){ 
      list.add(str); 
     } 

    String[] stringArr = list.toArray(new String[0]); 

    //copying and removing https from the list 

    List<String> list2 = new ArrayList<String>(); 
      Collections.addAll(list2, stringArr); 
      Iterator<String> iter = list2.iterator(); 
      while(iter.hasNext()){ 
       if(iter.next().contains(https)) 
        // here you should copy https lines to another file. 
        iter.remove(); 
      } 

      String[] stringArr2 = list2.toArray(new String[0]); 



     for (int i = 0; i<stringArr2.length; i++) { 
      //condition for pure domain names. 
      //else the action below 



      System.out.println(getDomainName(stringArr2[i]) + "," + stringArr2[i] + "," + "U" +"," + number_of_doc + "," + today); 
     } 




    } 

    public static String getDomainName(String url) throws URISyntaxException { 
    URI uri = new URI(url); 
    String domain = uri.getHost(); 
    return domain.startsWith("www.") ? domain.substring(4) : domain; 
} 





} 

回答

2

你爲什麼不拆:

String link = "https://stackoverflow.com/questions/ask "; 
if (link.split("/").length >= 3) { 
    System.out.println("CORRECT"); 
}else{ 
    System.out.println("NOT CORRECT"); 
} 

的理念是:分裂您的字符串/如果結果是大或等於3,然後再你的條件是正確的,否則不正確。

編輯

或類似的評論@biziclop提到你可以使用Guava's Splitter例如:

Iterable<String> result = 
     Splitter.on(CharMatcher.anyOf("/")). 
       limit(4). 
       split("https://stackoverflow.com/questions/ask"); 

if (Lists.newArrayList(result).size() > 3) { 
    System.out.println(Lists.newArrayList(result).get(3)); 
}else{ 
    System.out.println("NOTHING"); 
} 

輸入

https://stackoverflow.com/questions/ask 
https://stackoverflow.com 

輸出

questions/ask 
NOTHING 
+0

如果使用番石榴的'Splitter',你甚至可以指定一個上限您得到令牌的數量,所以你可以以後檢索所有內容第三個'/'作爲單個字符串。 – biziclop

+0

我看到這是個好主意@biziclop謝謝你,你的意思是這個'Splitter.on(CharMatcher.anyOf(「/」))。omitEmptyStrings()。split(「https://stackoverflow.com/questions/ask」 )' –

+0

差不多,你只需要不要調用'omitEmptyStrings()',而是調用'limit(4)'。這樣返回的第四個元素就是'questions/ask'。如果你得到的元素少於4個,你的字符串中沒有3'/'s。 – biziclop

1

您可以使用簡單的正則表達式:

String url = "https://web.whatsapp.com/"; 

    if(url.matches("\\w+://(\\w+.\\w+)+(.\\w+)*/(.+)")) 
     System.out.println("Correct URL"); 
    else 
     System.out.println("Incorrect URL"); 
相關問題