0

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!

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.