SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Question 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:
    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

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by mickyginger View Post
    Is there anyway to get an array of just the full matches, or even a multi-dimensional array of full matches and parenthesis matches
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    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:
    Code:
    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


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •