什么是正则表达式从url中查找路径参数?在url中使用正则表达式找到路径参数
http://localhost:8080/domain/v1/809pA8
https://localhost:8080/domain/v1/809pA8
想要使用正则表达式从上述URL检索值(809pA8),则优先使用java。
什么是正则表达式从url中查找路径参数?在url中使用正则表达式找到路径参数
http://localhost:8080/domain/v1/809pA8
https://localhost:8080/domain/v1/809pA8
想要使用正则表达式从上述URL检索值(809pA8),则优先使用java。
我会建议你做这样的事情
url.substring(url.lastIndexOf('/') + 1);
如果你真的喜欢正则表达式,你可以做
Matcher m = Pattern.compile("/([^/]+)$").matcher(url);
if (m.find())
value = m.group(1);
更喜欢正则表达式。 – user3157090 2015-02-12 08:48:25
为什么?这个问题对于需要正则表达式来说不够复杂。 – GoBusto 2015-02-12 08:51:07
我会尝试:
String url = "http://localhost:8080/domain/v1/809pA8";
String value = String.valueOf(url.subSequence(url.lastIndexOf('/'), url.length()-1));
无需正则表达式,我想。
编辑:对不起,我犯了一个错误:
String url = "http://localhost:8080/domain/v1/809pA8";
String value = String.valueOf(url.subSequence(url.lastIndexOf('/')+1, url.length()));
看到这个代码在这里工作:https://ideone.com/E30ddC
为您简单的情况下,正则表达式是矫枉过正,为他人注意。但是,如果你有更多的案例,这就是为什么你更喜欢正则表达式,如果你使用Spring,给Spring看一下AntPathMatcher#extractUriTemplateVariables。它实际上比直接使用正则表达式更适合提取路径变量。 Here are some good examples。
你有什么试过吗?你看过基于简单字符串函数的替代方法吗? – reto 2015-02-12 08:46:32
http://meta.stackoverflow.com/questions/285733 – GoBusto 2015-02-12 08:50:12
user3157090,请阅读[this](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – aioobe 2015-02-12 08:53:01