如何在Android Studio中使用正则表达式从给定的URL中提取子字符串

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.

这是我的方法的代码:

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

但这给了我失败!

评论
et_qui
et_qui

方法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 /

方法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.

点赞
评论
ysequi
ysequi

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);
    }
}
点赞
评论