Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to Match All Comments in a T-SQL Script

Tags:

regex

sql

tsql

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.

like image 697
bopapa_1979 Avatar asked Oct 07 '11 16:10

bopapa_1979


People also ask

Does T SQL support RegEx?

We use regular expressions to define specific patterns in T-SQL in a LIKE operator and filter results based on specific conditions. We also call these regular expressions as T-SQL RegEx functions. In this article, we will use the term T-SQL RegEx functions for regular expressions.

How do I comment in T SQL?

Comments can be inserted on a separate line or within a Transact-SQL statement. Multiple-line comments must be indicated by /* and */. A stylistic convention often used for multiple-line comments is to begin the first line with /*, subsequent lines with **, and end with */.

How do I comment multiple lines in SQL script?

Multi-line comments start with /* and end with */ . Any text between /* and */ will be ignored.


1 Answers

This should work:

(--.*)|(((/\*)+?[\w\W]+?(\*/)+))
like image 158
Jeremy Avatar answered Sep 25 '22 23:09

Jeremy