2016-12-05 79 views
0

我一直試圖讓子,從一個字符串的第三個斜槓(「/」)之後。得到第三個正斜槓後面的字符(「/」) - 使用正則表達式

http://www.google.com/search?q=Regular+Expressions而停止之前?和#如果它們出現在字符串中。

我的正則表達式:

Pattern regex = Pattern.compile(":\\/\\/[0-9a-zA-Z-\\.:]+(\\/)([^?#]*)$"); 

但它不每串

我也想出了正則表達式的工作:

Pattern regex = Pattern.compile("(.*)?:\\/\\/[^#?]*); 

然而,這一個抓住一切之前第三個正斜槓(「/」)。

我在做什麼錯? 感謝

+0

顯示樣品輸出這兩種情況下(?#和) – TheLostMind

+0

當你說「不與每一個工作字符串「,請顯示你測試的結果 –

+1

另外,你真的需要正則表達式嗎? 'indexOf'和'substring'可能工作得很好 –

回答

0

此正則表達式將在Java工作:

public static void main(String[] args) throws Exception { 
    String s = "http://www.google.com/search?q=Regular+Expressions"; 
    String regex = "(?:.*?/){2}.*?(/\\w+)(\\?|#).*"; // Don't capture anything upto the 3rd "/" then capture everything until you get a "?" or a "#" and then don't capture the rest. Replace everything with the captured value 
    String str = s.replaceAll(regex, "$1"); 
    System.out.println(str); 
    String s2 = "https://www.google.com/hello?test#"; 
    String str2 = s2.replaceAll(regex, "$1"); 
    System.out.println(str2); 

} 

O/P:

/search 
/hello 
1

你可以嘗試

(?:.*?\/){3}([^\/?#]+) 

或Java中

(?:.*?\\/){3}([^\\/?#]+) 

(逃跑反斜槓)。

匹配任何事情,包括一個斜槓 - 三次。然後捕捉一切達,包括,斜線,問號或井號。

結果是在捕獲組1

Check it out here at regex101

相關問題