msalihbindak
msalihbindak

Reputation: 622

How can I push regex matches to array in java?

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"

Upvotes: 1

Views: 545

Answers (2)

Andy Turner
Andy Turner

Reputation: 140554

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

Upvotes: 1

dounyy
dounyy

Reputation: 665

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

See also : How to negate the whole regex?

Upvotes: 1

Related Questions