Regular Expression to Match All Comments in a T-SQ

2020-01-29 06:40发布

I need a Regular Expression to capture ALL comments in a block of T-SQL. The Expression will need to work with the .Net Regex Class.

Let's say I have the following T-SQL:

-- This is Comment 1
SELECT Foo FROM Bar
GO

-- This is
-- Comment 2
UPDATE Bar SET Foo == 'Foo'
GO

/* This is Comment 3 */
DELETE FROM Bar WHERE Foo = 'Foo'

/* This is a
multi-line comment */
DROP TABLE Bar

I need to capture all of the comments, including the multi-line ones, so that I can strip them out.

EDIT: It would serve the same purpose to have an expression that takes everything BUT the comments.

标签: sql regex tsql
7条回答
等我变得足够好
2楼-- · 2020-01-29 07:21

This works for me:

(/\*(.|[\r\n])*?\*/)|(--(.*|[\r\n]))

It matches all comments starting with -- or enclosed within */ .. */ blocks

查看更多
登录 后发表回答