0

I'm trying to use regex in order to retrieve youtube video ID (embedded)

Assuming the following urls:

http://www.youtube.com/embed/f0Cn2g8ekMQ/
http://www.youtube.com/embed/f0Cn2g8ekMQ//
http://www.youtube.com/embed/f0Cn2g8ekMQ?param

I'd like to get the ID "f0Cn2g8ekMQ".

I was trying to do it this way:

regex: https?://www\.youtube\.com/embed/(\S+)[/|\?]?.*

But it seems like the or operator doesn't work for me and the ID I recieve include the "/" or "?" and the rest of the string.

Is there any good way to do it with regex?

Thanks!

3 Answers 3

1

This should work for you. Note the escaped / (slashes)

/https?:\/\/www\.youtube\.com\/embed\/([^\/?]+)/g

https://regex101.com/r/57JeRU/1

For details, also check the code generator for JAVA.

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

5 Comments

Thanks. But ask far as I know you don't have to escape slashes, am I right?
Depends on the programming language or tool you are using. As I stated: check the code generator for details on the proper way to do this in JAVA code.
It works with java parser with or without escaping them.
Thanks. but shouldn't the question mark be escaped too?
@idogo this is not needed for ? (and . (dot)) within a [] character class
0

If you are very sure that the structure of the url is alway following the example you are using the you can use this:

    try{
        String add1 = "http://www.youtube.com/embed/f0Cn2g8ekMQ/";
        String add2 = "http://www.youtube.com/embed/f0Cn2g8ekMQ//";
        String add3 = "http://www.youtube.com/embed/f0Cn2g8ekMQ?param";

        String []all1 = add1.replace("//", "/").split("[/?]");
        String []all2 = add2.replace("//", "/").split("[/?]");
        String []all3 = add3.replace("//", "/").split("[/?]");

        System.out.println(all1[3]);
        System.out.println(all2[3]);
        System.out.println(all3[3]);
    }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("URL format changed");
        //Do other things here if url structure changes
    }

Output

f0Cn2g8ekMQ
f0Cn2g8ekMQ
f0Cn2g8ekMQ

Comments

0

You can use this regex \/embed\/(\w+)[\/?] not you can get the result like so :

String[] str = {"http://www.youtube.com/embed/f0Cn2g8ekMQ/",
    "http://www.youtube.com/embed/f0Cn2g8ekMQ//",
    "http://www.youtube.com/embed/f0Cn2g8ekMQ?param"};

Pattern p = Pattern.compile("\\/embed\\/(\\w+)[\\/?]");
Matcher m;
for (String s : str) {
    m = p.matcher(s);
    if (m.find()) {
        System.out.println(m.group(1));
    }
}

Outputs

f0Cn2g8ekMQ
f0Cn2g8ekMQ
f0Cn2g8ekMQ

Ideone demo

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.