How to extract id from url? Google sheet

I have the following links.

https://docs.google.com/spreadsheets/d/1mrsetjgfZI2BIypz7SGHMOfHGv6kTKTzY0xOM5c6TXY/edit#gid=1842172258
https://docs.google.com/a/example.com/spreadsheets/d/1mrsetjgfZI2BIypz7SGHMOfHGv6PTKTzY0xOM5c6TXY/edit#gid=1842172258
https://docs.google.com/spreadsheets/d/1mrsetjgfZI2BIypz7SGHMOfHGv6kTKTzY0xOM5c6TXY

      

Foreach url, I need to extract the sheet id: 1mrsetjgfZI2BIypz7SGHMOfHGv6PTKTzY0xOM5c6TXY

into a java string.

I am thinking to use split , but it cannot work with all test cases:

String string = "https://docs.google.com/spreadsheets/d/1mrsetjgfZI2BIypz7SGHMOfHGv6kTKTzY0xOM5c6TXY/edit#gid=1842172258";
String[] parts = string.split("/");
String res = parts[parts.length-2];
Log.d("hello res",res );

      

How can i do this?

+3


source to share


3 answers


it looks like the id you are looking for always follows "/ spreadsheets / d /", if so you can update your code to that



        String string = "https://docs.google.com/spreadsheets/d/1mrsetjgfZI2BIypz7SGHMOfHGv6kTKTzY0xOM5c6TXY/edit#gid=1842172258";
        String[] parts = string.split("spreadsheets/d/");
        String result;
        if(parts[1].contains("/")){
            String[] parts2 = parts[1].split("/");
            result = parts2[0];
        }
        else{
            result=parts[1];
        }
        System.out.println("hello "+ result);

      

+1


source


You can use regex \/d\/(.*?)(\/|$)

( regex demo ) to solve your problem, if you look closer you can see that the id exists between d/

and /

or end of line

for that you can get everything in between, check this code demo:

String[] urls = new String[]{
    "https://docs.google.com/spreadsheets/d/1mrsetjgfZI2BIypz7SGHMOfHGv6kTKTzY0xOM5c6TXY/edit#gid=1842172258",
    "https://docs.google.com/a/example.com/spreadsheets/d/1mrsetjgfZI2BIypz7SGHMOfHGv6PTKTzY0xOM5c6TXY/edit#gid=1842172258",
    "https://docs.google.com/spreadsheets/d/1mrsetjgfZI2BIypz7SGHMOfHGv6kTKTzY0xOM5c6TXY"
};
String regex = "\\/d\\/(.*?)(\\/|$)";

for (String url : urls) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(url);

    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }
}

      



results

1mrsetjgfZI2BIypz7SGHMOfHGv6kTKTzY0xOM5c6TXY
1mrsetjgfZI2BIypz7SGHMOfHGv6PTKTzY0xOM5c6TXY
1mrsetjgfZI2BIypz7SGHMOfHGv6kTKTzY0xOM5c6TXY

      

+2


source


Using a regular expression

Pattern pattern = Pattern.compile("(?<=\\/d\\/)[^\\/]*");
Matcher matcher = pattern.matcher(url);
System.out.println(matcher.group(1));

      

Using Java

String result = url.substring(url.indexOf("/d/") + 3);
int slash = result.indexOf("/");
result =  slash == -1 ? result
                      : result.substring(0, slash);
System.out.println(result);

      

0


source







All Articles