2016-01-06 51 views
0

我需要從URL獲取此字符串 - 「start = 100」,start可以從0更改爲1000+。 就像我曾嘗試正則表達式 -正則表達式 - 從URL中獲取值

Pattern p5 = Pattern.compile(".*start=[0-9]+.*"); 
    Pattern p6 = Pattern.compile(".*start=\\d+.*"); 
    Pattern p7 = Pattern.compile(".*start=.*"); 
    Pattern p8 = Pattern.compile(".*(start=[0-9]+).*"); 

似乎沒有任何工作:(

+1

使用'start = \\ d +'而不將它放在'。*'中。 – ndn

+0

向我們展示更多代碼。 –

回答

1

如果添加()到你的第2正則表達式的例子之一,或者如果您使用4 例如,你可以得到你想要的輸出

public static void main(String[] args) { 
    String url = "http://localhost:8080/x?start=100&stop=1000"; 
    Pattern p = Pattern.compile(".*(start=[0-9]+).*"); 
    Matcher m = p.matcher(url); 
    if (m.find()) { 
     // m.group(0) - url 
     // m.group(1) - the first group (in this case - it's unique) 
     System.out.println(m.group(1)); 
    } 
} 

輸出:

start=100 
0

根據代碼中URL的存在方式(可能不是字符串而是URI),您可能會使用此代碼段中的某些部分。

URI uri = new URI("http://localhost:8080/x?start=10&stop=100"); 
String[] params = uri.getQuery().split("&"); 
for (String param : params) { 
    if (param.startsWith("start=")) { 
     System.out.println(param); 
     break; 
    } 
}