Q:

Regex captures characters on same line

I have this regex, and it captures things on the same line if there's no space after the link.
The regex is:
(?:http\:\/\/)?(?:www\.)?ama?zo?n\.(?:com|ca|co\.uk|co\.jp|de|fr)/(?:exec/obidos/ASIN/|o/|gp/product/|(?:(?:[^"\'/]*)/)?dp/|)(B[A-Z0-9]{9})(?:(?:/|\?|\#)(?:[^"\'\s]*))?

My expected input is 
[link](http://www.amazon.com/dp/B00CTUER1M)

Here is[a cool toy](http://www.amazon.com/dp/B00CTUER1M/ref=gb1h_img_e-4_8722_fb086345?smid=ATVPDKIKX0DER)!dddd fdsfsdfds

I expect the output to be 
[link](http://www.amazon.com/dp/B00CTUER1M?tag=affcode-20)

Here is[a cool toy](http://www.amazon.com/dp/B00CTUER1M?tag=affcode-20)!dddd fdsfsdfds

However for the second one I get 
Here is[a cool toy](http://amazon.com/dp/B00CTUER1M/?tag=affcode-20 fdsfsdfds

A:

From the looks of it, you left out a close parenthesis ) from the final negative character class.  
 # (?:http://)?(?:www\.)?ama?zo?n\.(?:com|ca|co\.uk|co\.jp|de|fr)/(?:exec/obidos/ASIN/|o/|gp/product/|(?:(?:[^"'/]*)/)?dp/|)(B[A-Z0-9]{9})(?:(?:/|\?|\#)(?:[^"'\s)]*))?

 (?: http:// )?
 (?: www \. )?
 ama? zo?n \.
 (?:
      com
   |  ca
   |  co \. uk
   |  co \. jp
   |  de
   |  fr 
 )
 /
 (?:
      exec/obidos/ASIN/
   |  o/
   |  gp/product/
   |  (?:
           (?: [^"'/]* )
           /
      )?
      dp/
   |  
 )
 ( B [A-Z0-9]{9} )             # (1)
 (?:
      (?: / | \? | \# )
      (?: [^"'\s)]* )               # <- Add ')' to negative class
 )?

