Anthony Faull
Anthony Faull

Reputation: 17957

Regex replace with capturing groups

I wish to refactor code using .NET regular expressions. The aim is to split declarations and assignments (for backwards compatibility with SQL 2005).

Sample Input:

DECLARE @clientCode char(10), @city nvarchar(100) = '', @country char(2) = 'US',
   @clientId int

Desired Output:

DECLARE @clientCode char(10), @city nvarchar(100), @country char(2),
   @clientId int
SELECT @city = '', @country = 'us'

This is what I have so far to match the input:

DECLARE\s+
(
    ,?
    (@\w+\s+)
    (\(.+\))?
    (\=\s+\w+)?
)+

What replacement regex could I use to get the expected output?

Upvotes: 0

Views: 305

Answers (2)

David Brabant
David Brabant

Reputation: 43459

Well, just for the fun of it, if you happen to have SQL Server 2012 feature pack at hand, you might use Microsoft.SqlServer.Management.SqlParser.Parser to parse your existing SQL 20xx code and generate the equivalent 2005 code. You might even do so with PowerShell. Nice weekend project, eh? :-)

Upvotes: 1

Nick Butler
Nick Butler

Reputation: 24383

Even if you get this working with a RegEx, it will be a maintenance nightmare.

I suggest you write out some well commented string manipulation in code.

Upvotes: 1

Related Questions