const regex = /(?<=AS \()([^\(\)]*(\([^\(\)]*\))?[^\(\)]*)*(?=\))/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<=AS \\()([^\\(\\)]*(\\([^\\(\\)]*\\))?[^\\(\\)]*)*(?=\\))', 'gm')
const str = `WITH Sales_Cust_Join_CTE
AS ( SELECT fs.OrderDateKey,fs.ProductKey,fs.OrderQuantity ,fs.UnitPrice AS TotalSale ,dc.FirstName,dc.LastName FROM [dbo].[FactInternetSales] fs INNER JOIN [dbo].[DimCustomer] dc ON dc.CustomerKey = fs.CustomerKey ) ,Date_CTE
AS ( SELECT DateKey ,CalendarYear FROM [dbo].[DimDate] )
SELECT CalendarYear ,ProductKey ,SUM(TotalSale) AS TotalSales
FROM Sales_Cust_Join_CTE
INNER JOIN Date_CTE ON Date_CTE.DateKey = Sales_Cust_Join_CTE.OrderDateKey
GROUP BY CalendarYear ,ProductKey
ORDER BY CalendarYear ASC ,TotalSales DESC
`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
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 JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions