4

我正在使用正则表达式来解析存储过程以修改它们。这是我的示例文本:

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) 

...

我只想得到这部分:

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)
)

请注意,它可能会重复多次。我想要文本中所有临时表的声明。我使用了以下常规模式:

string re1 = "(Declare)( )(@)((?:[a-z][a-z0-9_]*))(\\s+)(Table)(\\s+)(\\(.*\\))";
Regex r = new Regex(re1, RegexOptions.Multiline | RegexOptions.IgnoreCase);

但它不起作用。有任何想法吗?

4

3 回答 3

1

试试这个Regex

DECLARE\s+@(\w+)\s+TABLE\s+\(([^,\(\)]+(\(\d+\))?(,)?)+\)

和示例代码:

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();
于 2012-10-27T05:52:31.377 回答
1

你必须使用singleline模式而不是 multiline模式

将此regexsingleline模式一起使用

declare\s*@(?:[a-z]\w*)\s*table.*?\)\s*\)

所以,应该是

string re1 = @"declare\s*@(?:[a-z]\w*)\s*table.*?\)\s*\)";
Regex r = new Regex(re1 ,RegexOptions.Singleline | RegexOptions.IgnoreCase );

在这里试试

于 2012-10-27T08:08:58.830 回答
0

你需要得到平衡支架

Regex rx = new Regex(@"declare\s\@([a-zA-Z_][a-zA-Z0-9_]*)\w+table\w*\(((?<BR>\()|(?<-BR>\))|[^()]*)+\)");
于 2012-10-27T06:17:49.340 回答