简体   繁体   中英

Remove everything before and after a string part in Android

I want to get Amazon product ASIN from the URL here are some examples:

https://www.amazon.com/Premium-Flagship-Lenovo-Processor-Bluetooth/dp/B07H15QHT6/ref=sr_1_2_sspa?s=pc&ie=UTF8&qid=1537733386&sr=1-2-spons&keywords=laptop&psc=1


https://www.amazon.com/Youve-Got-Crabs-Creators-Exploding/dp/B07BKLT9B5/ref=mp_s_a_1_1?ie=UTF8&qid=1537733019&sr=8-1-spons&pi=AC_SX236_SY340_FMwebp_QL65&keywords=games&psc=1

I want to get that text after /dp/ and remove everything after that text like this

B07BKLT9B5 and B07H15QHT6

You can use:

split("dp") 

And get 2 part or use substring() and indexOf() method.

You can do something like that

public String getCode(String s) {
    int pos = s.indexOf("/dp/"); // find the position of the string "/dp/" in the url
    String substr = s.substring(pos + "/dp/".length()); // get everyting after dp
    String[] parts = substr.split("/"); // split at every '/' character
    return parts[0]; // your result will be the first element of the array
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM