$re = '/\)\s+references\s+(?:\[.+?\](?:\.\[.+?\])*)\s+\((\[(.+?)\](,\[(.+?)\])*)\)\s+on\s+/m';
$str = 'Alter table [xxx].[sRISRESPPol] add Constraint [FK_cUcZnak_sRISRESPPol] foreign key([IdUcZnak],[IfUcZnak],[huhu]) references [dbo].[dbo].[cUcZnak] ([xx],[Id],[FirstId]) on update no action on delete no action
var regexFK = /\\]\\s+?foreign\\s+?key\\((\\[(.+?)\\](,\\[(.+?)\\])*)\\)\\s+?references\\s+?\\[/g;
var regexPrimaryTable = /\\)\\s+references\\s+(?:\\[.+?\\]\\.)*\\[(.+?)\\]\\s+\\(/g;
foreignTable ^Alter\\s+?table\\s+?(?:\\[.+?]+?\\]\\.)*\\[(.+?)\\]\\s+?add\\s+?Constraint\\s+?\\[
PK \\)\\s+references\\s+(?:\\[.+?\\](?:\\.\\[.+?\\])*)\\s+\\((\\[(.+?)\\](,\\[(.+?)\\])*)\\)\\s+on\\s+
M1 112-173 ) references [dbo].[dbo].[cUcZnak] ([xx],[Id],[FirstId]) on
G1 148-167 [xx],[Id],[FirstId]
G2 149-151 xx
G3 157-167 ,[FirstId]
G4 159-166 FirstId';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php