user5481342 user5481342 - 2 months ago 14
Java Question

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

I want to take only simple video link with this expression


when I use this code :

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

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

for (String t : tokenVal) {

It prints


I want to output be like this:



"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.
""      // 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:\\/\\/\\/watch\\?v=.{11}");
Matcher matcher = pattern.matcher(ytLink);
if (matcher.find()) {

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