[英]How to get a segment of an Url
I have an URL https://example.com/A_segment/B_segment/ref=abc
.我有一个 URL https://example.com/A_segment/B_segment/ref=abc
。 Is there a way to extract B_segment
out of it?有没有办法从中提取B_segment
?
*The URL is not always the same but B_segment always follow A_segment and ahead of ref=. *URL 并不总是相同的,但 B_segment 总是跟在 A_segment 之后并在 ref= 之前。
Assuming URL can also be in form http://server.domain/what/ever/A_segment/xxxx/ref=123
and that you are interested in xxxx
part you can use regex to find part /A_segment/(.+)/ref=
.假设 URL 也可以是http://server.domain/what/ever/A_segment/xxxx/ref=123
并且您对xxxx
部分感兴趣,您可以使用正则表达式来查找部分/A_segment/(.+)/ref=
. Part (.+)
represents one or more of any characters and because of parenthesis it will be placed in group (here indexed as 1
since it is first (and only) group) to let us grab only match from that group.部分(.+)
代表一个或多个任何字符,并且由于括号,它将被放置在组中(这里索引为1
因为它是第一个(也是唯一的)组)让我们只从该组中获取匹配项。
String url = "http://server.domain/what/ever/A_segment/xxxx/ref=123";
Pattern p = Pattern.compile("/A_segment/(.+)/ref=");
Matcher m = p.matcher(url);
if (m.find()){
String result = m.group(1); //<-get match from group 1
System.out.println(result); //Output: xxxx
} else {
//here you can throw exception or return some default value in case of lack of match
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.