Reputation: 199
I'm using regular expression to parse stored procedures in order to modify them. here is my sample text:
DECLARE @TempTable TABLE
(
TempID int IDENTITY PRIMARY KEY,
AMFID smallint,
AppModID smallint,
AppID tinyint,
ModID smallint,
FPID smallint,
URL varchar(100),
SortIndex smallint,
[AppName] varchar(100),
ModName varchar(100),
FPName varchar(100),
WUCData varchar(7000)
)
-- Fill the temp table
INSERT INTO @TempTable
(
AMFID,
AppModID,
AppID,
ModID,
FPID,
URL,
SortIndex,
[AppName],
ModName,
FPName,
WUCData
)
SELECT
siAppModFP.AMFID,
siAppModFP.AppModID,
siAppModule.AppID,
siAppModule.ModID,
siAppModFP.FPID,
siAppModFP.URL,
siAppModFP.SortIndex,
siApplication.[AppName],
siModule.ModName,
siFP.FPName,
dbo.funcGetAppModFPWUC(siAppModFP.AMFID)
FROM siApplication WITH (NOLOCK)
...
I just want to get this part:
DECLARE @TempTable TABLE
(
TempID int IDENTITY PRIMARY KEY,
AMFID smallint,
AppModID smallint,
AppID tinyint,
ModID smallint,
FPID smallint,
URL varchar(100),
SortIndex smallint,
[AppName] varchar(100),
ModName varchar(100),
FPName varchar(100),
WUCData varchar(7000)
)
Notice it might be repeated more than once. I want all declarations of temp tables in the text. I used following regular pattern:
string re1 = "(Declare)( )(@)((?:[a-z][a-z0-9_]*))(\\s+)(Table)(\\s+)(\\(.*\\))";
Regex r = new Regex(re1, RegexOptions.Multiline | RegexOptions.IgnoreCase);
But it's not working. Any ideas?
Upvotes: 4
Views: 337
Reputation: 32817
You have to use singleline
mode not multiline
mode
Use this regex
with singleline
mode
declare\s*@(?:[a-z]\w*)\s*table.*?\)\s*\)
So,it should be
string re1 = @"declare\s*@(?:[a-z]\w*)\s*table.*?\)\s*\)";
Regex r = new Regex(re1 ,RegexOptions.Singleline | RegexOptions.IgnoreCase );
try it here
Upvotes: 1
Reputation: 10347
Try this Regex
:
DECLARE\s+@(\w+)\s+TABLE\s+\(([^,\(\)]+(\(\d+\))?(,)?)+\)
and a sample code:
var pattern = @"DECLARE\s+@(\w+)\s+TABLE\s+\(([^,\(\)]+(\(\d+\))?(,)?)+\)";
var matches = Regex.Matches(inputText, pattern);
foreach(Match match in matches)
Output.Lines.Add(match.ToString());
// or in LINQ way
var result = from Match match in matches select match.ToString();
Upvotes: 1
Reputation: 3638
You need to get balancing brackets
Regex rx = new Regex(@"declare\s\@([a-zA-Z_][a-zA-Z0-9_]*)\w+table\w*\(((?<BR>\()|(?<-BR>\))|[^()]*)+\)");
Upvotes: 0