1

I've currently got a string, of which I want to use certain parts. With these parts I want to do various things, like pushing them to an array or showing them in a text area.

Fist I try to split method. It delete my regex matches and prints other part of string. I want to delete other part and print the regex match.

How can I do this?

For example:
There are lot of youtube links like this

https://www.youtube.com/watch?v=qJuoXM7G322&list=PLRfAW_jVDn06M7qxHIwlowgLY3Io1pG6z&index=7

I want to take only simple video link with this expression

"https:\\/\\/www.youtube.com\\/watch\\?v=.{11}"

when I use this code :

    String ytLink = linkArea.getText();
    String regexp = "https:\\/\\/www.youtube.com\\/watch\\?v=.{11}";
    String[] tokenVal;
    tokenVal = ytLink.split(regexp);

    System.out.println("Count of Links : "+tokenVal.length);

    for (String t : tokenVal) {
        System.out.println(t);
    }

It prints

"&list=PLRfAW_jVDn06M7qxHIwlowgLY3Io1pG6z&index=7"

I want to output be like this:

"https://www.youtube.com/watch?v=SATL2mTfZO0"
1
  • 1
    Can you please post at least one example so that we can go from there? Commented Nov 13, 2015 at 13:15

2 Answers 2

1

"when I Right this code :"

You are splitting the string with that regular expression, which is not the correct tool for the job.

It is dividing your example string into:

""                                                 // The bit before the separator.
"https://www.youtube.com/watch?v=qJuoXM7G322"      // The separator
"&list=PLRfAW_jVDn06M7qxHIwlowgLY3Io1pG6z&index=7" // The bit after the separator

but then discarding the separator, so you'd get back a 2-element array containing:

""                                                 // The bit before the separator.
"&list=PLRfAW_jVDn06M7qxHIwlowgLY3Io1pG6z&index=7" // The bit after the separator

If you want to get the thing that matches the regex, you'd need to use Pattern and Matcher:

Pattern pattern = Pattern.compile("https:\\/\\/www.youtube.com\\/watch\\?v=.{11}");
Matcher matcher = pattern.matcher(ytLink);
if (matcher.find()) {
  System.out.println(matcher.group());
}

(I don't entirely trust your escaped backslashes in your regular expression; however the pattern is not really important to the principle)

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

3 Comments

it works for 1 link. If it can work for many links. it will OK.
Change if to while. Read the documentation for java.util.regex.Matcher.
OK every thing is ok. Thanks a lot :)
1

You can negate your regex using the negative lookaround: (?!pattern)

See also : How to negate the whole regex?

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.