简体   繁体   中英

How can I extract substring from the given url using regex in Android Studio

I'm trying to extract CANseIqFMnf from the URL https://www.instagram.com/p/CANseIqFMnf/ using regex in Android studio. Please help me to get a regex expression eligible for Android Studio.

Here is the code for my method:

String url = "https://www.instagram.com/p/CANseIqFMnf/";
    String REGEX = "/p\//";
    Pattern pattern = Pattern.compile(REGEX);
    Matcher matcher = pattern.matcher(url);

    boolean match = matcher.matches();

    if (match){
        Log.e("success", "start = " + matcher.start() + " end = " + matcher.end() );
    }else{
        Log.e("failed", "failed");
    }

But it gives me failed in return!

Method 1

You just need to use replaceAll method in String , no need to compile a pattern and complicate things:

String input = "https://www.instagram.com/p/CANseIqFMnf/";
String output = input.replaceAll("https://www.instagram.com/p/", "").replaceAll("/", "");
Log.v(TAG, output);

Note that the first replaceAll is to remove the url and the second replaceAll is to remove any slashes /

Method 2

Pattern pattern = Pattern.compile("https://www.instagram.com/p/(.*?)/");
Matcher matcher = pattern.matcher("https://www.instagram.com/p/CANseIqFMnf/");
        while(matcher.find()) {
            System.out.println(matcher.group(1));
        }

Note that if matcher.find() returns true then if you used modifiers like this in your REGEX (.*?) then the part found there will be in group(1) , and group(0) will hold the entire regex match which is in your case the entire url.

Alternate option w/o regex can be implemented in a simpler manner as below using java.nio.file.Paths APIs

public class Url {

    public static void main(String[] args) {
        String url = "https://www.instagram.com/p/CANseIqFMnf/";
        String name = java.nio.file.Paths.get(url).getFileName().toString();
        System.out.println(name);
    }
}

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