Java:从URL获取整数值

时间:2011-11-01 09:44:47

标签: java regex

您好我正在尝试从URL中获取字符串。

我正在使用正则表达式。

String url = "http://localhost/htc/android/htc-incredible/259164-gpid";
Pattern regex = Pattern.compile("^.+/(\\d+)-gpid$"); 
Matcher tagmatch = regex.matcher( url );
System.out.println(tagmatch.group(0));

错误:

Exception in thread "main" java.lang.IllegalStateException: No match found

我做错了什么:

3 个答案:

答案 0 :(得分:3)

您需要使用group(1)(第一个捕获组的内容),而不是group(0)(整个匹配)。

哦,当然你需要实际进行搜索:

tagmatch.find();
System.out.println(tagmatch.group(1));

答案 1 :(得分:1)

或者,您可以将lastIndexOfsplit结合使用,以获取所需网址的一部分。代码看起来像这样

url.substring(url.lastIndexOf('/')+1).split("-")[0] //prints 259164

答案 2 :(得分:1)

你可以试试这个:

String url = "http://localhost/htc/android/htc-incredible/259164-gpid";
url.substring(url.indexOf('/',url.indexOf("htc-incredible/"))+1,url.indexOf("-gpid"));