I have an URL https://example.com/A_segment/B_segment/ref=abc
. Is there a way to extract B_segment
out of it?
*The URL is not always the same but B_segment always follow A_segment and ahead of 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=
. 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.
Demo :
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.