簡體   English   中英

Java:從URL獲取整數值

[英]Java: Get integer value from URL

嗨,我正在嘗試從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

我做錯了什么:

您需要使用group(1) (第一個捕獲組的內容),而不是group(0) (整個匹配項)。

哦,當然,您需要實際進行搜索:

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

您可以嘗試以下方法:

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

另外,您可以結合使用lastIndexOfsplit來獲取所需的部分網址。 代碼將如下所示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM