在文件中搜索Catch Throw(正则表达式?)

时间:2014-03-21 22:06:11

标签: regex search wildcard

我必须修复一些异常处理代码,其中基本异常不作为内部异常传递

例如:

Try
    SomeFunction()
Catch ex As Exception
    If ex.Message = somePreDefinedExceptionMessage Then
        LogErrorMsg(ex.Message)
    Else
        Throw New Exception(ex.Message) //<--- PROBLEM
End Try

正如您所看到的,原始异常未被执行,我需要它。我需要搜索解决方案中的所有文件并修复上述示例中的任何内容。我的问题是如何在其中搜索带有投掷的捕获物?这样我就可以查看是否正在传入捕获的异常。

编辑: 为清楚起见,我需要找到与一般模式匹配的任何文本块:

Catch
    //bunch of crap
    Throw //anything
    //potentially more crap (should only be whitespace/newlines)
End Try

3 个答案:

答案 0 :(得分:0)

也许如果你这样说,你会得到你需要的东西

Try
    SomeFunction()
Catch ex As Exception
    If ex.Message = somePreDefinedExceptionMessage Then
        LogErrorMsg(ex.Message)
    Else
        Throw ex
End Try

答案 1 :(得分:0)

这可能会有所帮助:http://geekswithblogs.net/akraus1/archive/2010/05/29/140147.aspx

我尝试'抓住。(。 \ n)*?。*抛出'在Ctrl-F窗口中(并选择使用正则表达式),它发现捕获后跟抛出..

答案 2 :(得分:0)

我在这里发现了类似的情况:https://stackoverflow.com/a/20109055/2136840

调整该解决方案,这对我来说很有用:

/(?<!End )Try(?:[^TE]+|T(?!hrow)|E(?!nd Try))*Throw.*?End Try/gs

解析你得到的正则表达式:

(?<!End )Try   #find a Try not immediately preceded by an End

(?:[^TE]+|T(?!hrow)|E(?!nd Try))*   #take every character after that that isn't a T or E or is a T or E that isn't part of "Throw" or "End Try", respectively

Throw.*?End Try   #continue grabbing a Throw, any additional characters, and an End Try

gs   #global - match multiple, single-line (confusing name for having the dot match newline characters)

如果它到达最后一部分并且在结束尝试之前没有投掷,它将丢弃整个块。

所以用英语把它放在一起,你就“找到一个尝试不会立即在一个结束之前;然后取出所有后续角色,直到你进入一个投掷,然后按顺序结束尝试。”

为了测试这个,我在Perl中运行了这个:

my $str = <<EOS;
    Try
        SomeFunction()
    Catch ex As Exception
        If ex.Message = somePreDefinedExceptionMessage Then
            LogErrorMsg(ex.Message)
        Else
            Throw New Exception(ex.Message) //<--- PROBLEM
    End Try

    'Other Code

    Try
        SomeFunction()
    Catch ex As Exception
        If ex.Message = somePreDefinedExceptionMessage Then
            LogErrorMsg(ex.Message)
        Else
            Throw New Exception(ex.Message) //<--- PROBLEM
    End Try

    Try
        SomeFunction()
    Catch ex As Exception
        If ex.Message = somePreDefinedExceptionMessage Then
            LogErrorMsg(ex.Message)
    End Try

    Try
        SomeFunction()
    Catch ex As Exception
        If ex.Message = somePreDefinedExceptionMessage Then
            LogErrorMsg(ex.Message)
    End Try

    'Other Code

    Try
        SomeFunction()
    Catch ex As Exception
        If ex.Message = somePreDefinedExceptionMessage Then
            LogErrorMsg(ex.Message)
        Else
            Throw New Exception(ex.Message) //<--- PROBLEM
    End Try

EOS

while ($str =~ /(?<!End )Try(?:[^TE]+|T(?!hrow)|E(?!nd Try))*Throw.*?End Try/gs) {
    print "Next Error: " . $& . "\r\n\r\n";
}

注意:语法高亮似乎不像Perl的heredoc。

修改:如果您只想要捕获阻止,请使用Catch代替(?<!End )Try