非贪婪的负面看法

时间:2016-04-07 21:07:35

标签: c# regex

在C#中,我正在尝试编写一个正则表达式,该表达式将查找所有go语句,这些语句是该行上唯一的语句,而不是紧接在use $(trop)语句之前。

我非常接近 - 它正在查找所有go语句,但我无法做到正确 - 它正在找到第一个(如下面标有“请勿抓住这个”),但我我无法使负面的背后工作正常。任何人都可以帮我解决我做错的事吗?

(?<goStatement>^(\s{0,})go(\s{0,})$)(?<useTrop>(?<!(^\s{0,}use \(trop\)\s{0,}$)))`

以下是我正在搜索的文字:

set noexec off
:setvar trop devtip
:setvar trop_wf_tracking trop_workflow_tracking
:setvar trop_wf trop_wf

-- Information - to set this script to only run once change stop_if_applied to 1.
:setvar stop_if_applied 1


-- Do NOT catch this one
use $(trop)
go



if $(stop_if_applied) = 1 and exists (select * from $(trop).dbo.DATABASE_VERSION where DB_SCRIPT_NUMBER = 20656) begin
    select 'This db script has already been run.  If it is required to run again change the variable stop_if_applied to 0.  Disabling all further commands on the connection.'
          ,* from $(trop).dbo.DATABASE_VERSION 
    where DB_SCRIPT_NUMBER = 20656

    set noexec on
    return
end

-- DO catch this one ----------
go
-- ------------------------------------------------------------------------------

set xact_abort on

begin transaction

select * from $(trop).dbo.DATABASE_VERSION where DB_SCRIPT_NUMBER = 20656;

/* Insert your code here */

select * from dbo.SECURITY_RIGHT 
-- DO catch this one ----------
go

/* End of your code here */
-- DO catch this one ----------
go

if not exists (select * from $(trop).dbo.DATABASE_VERSION where DB_SCRIPT_NUMBER = 20656)
    insert into $(trop).dbo.DATABASE_VERSION (DB_SCRIPT_NUMBER, COMMENT)
    values (20656, 'comment goes here');

select * from $(trop).dbo.DATABASE_VERSION where DB_SCRIPT_NUMBER = 20656;

commit

2 个答案:

答案 0 :(得分:1)

是的,后视应该在^go之前。

 (?m)                              # Multi-line mode
 (?<! use \s* \$\(trop\) \s* )     # Not a 'use $(trop)` behind 
 ^                                 # Beginning of line
 \s* go                            # The 'go'
 [^\S\r\n]*                        # Optional horizontal whitespace
 (?= \r? \n | $ )                  # until the end of line or EOS

C#test

 Regex RxGo = new Regex(@"(?m)(?<!use\s*\$\(trop\)\s*)^\s*go[^\S\r\n]*(?=\r?\n|$)");
 Match matchGo = RxGo.Match(sTarget);
 while (matchGo.Success)
 {
    Console.WriteLine("'{0}'", matchGo.Value);
    matchGo = matchGo.NextMatch();
 }

答案 1 :(得分:0)

你应该能够使用它:

(?<!(use \$\(trop\)[\r\n]))^go$

这至少适用于你的例子。