Regex.match with parenthesis

Hi there,

I’m trying out a regex to match urls, and my expression needs to contain parentheses. If I were using PHP’s preg_match_all function it would return a multi-dimensional array of matches, and then each match in parenthesis.

As far as i can make out from my research online, javascript’s match function with the /g modifier will behave in a simliar way, returning an array of matches. All good in da hood, except when parentheses appear in the regex.

Here’s my regex:

/(https?:\/\/)?www\.[-a-zA-Z0-9_]+\.[a-z\.]{3,5}(\/[-a-zA-Z0-9\?\=]+)?/gi

Now, on a string like this:

www.youtube.com/watch?=aBgFFdpn www.movemakeshake.co.uk/move

I get this array:

matches[0]: www.youtube.com/watch?=aBgFFdqn
matches[1]: undefined
matches[2]: /watch?=aBgFFdpn

Is there anyway to get an array of just the full matches, or even a multi-dimensional array of full matches and parenthesis matches, or is there a better way of approaching this?

Many thanks,
Mike

JavaScript isn’t that mature when using the exec method, but there’s nothing stopping you from creating a function that processes the results and returns an array of results.
The RegExp exec documentation has some code (below the table) that makes for a useful starting-off point.

Then again, have you investigated using the string.match method instead.

Hi Paul, thanks for your post.

This was confusing me for sometime, but thanks to you I managed to get what I wanted using the match method:


re = /(https?:\\/\\/)?www\\.[-a-zA-Z0-9_]+\\.[a-z\\.]{3,5}(\\/[-a-zA-Z0-9\\?\\=]+)?/gi
string = //string to match here...
matches = string.match(re);

which returned the array of matches I wanted.

Many thanks,
Mike