2016-01-06 50 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; 
    } 
}