Extract substring after specific pattern

I have the following line:

http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true

How can I remove the part after 30/? In this case, he 32531a5d-b0b1-4a8b-9029-b48f0eb40a34. I have other lines having the same part up to 30 /, after which each line has a different id until the next / that I want.

+5
source share
4 answers

splitThe class function Stringwill not help you in this case, because it discards the delimiter and this is not what we want here. you need to make a pattern that looks behind. Syntax Appearance:

(?<=X)Y

Which identifies anyone Ythat is preceded X.

So, in this case you will need this template:

(?<=30/).*

, , :

String input = "http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true";
Matcher matcher = Pattern.compile("(?<=30/).*").matcher(input);
matcher.find();
System.out.println(matcher.group());
+3

:

String s = "http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true";
        System.out.println(s.substring(s.indexOf("30/")+3, s.length()));
+6

?

String[] out = mystring.split("/")
return out[out.length - 2]

I think / is definitely the separator you are looking for. I do not see the problem you are talking about in Alex

EDIT: Ok, Python got me with indexes.

+2
source

Regular expression is the answer I think. However, how the expression is written depends on the data format (url) you want to process. Like this:

    Pattern pat = Pattern.compile("/Content/SiteFiles/30/([a-z0-9\\-]+)/.*");
    Matcher m = pat.matcher("http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true");
    if (m.find()) {
        System.out.println(m.group(1));
    }
+1
source

All Articles