首页 > 解决方案 > 需要帮助以了解 1 有效而 1 无效的类似 RegExp 用法之间的区别

问题描述

我是 stackoverflow 的忠实粉丝,虽然我不熟悉使用正则表达式。我编写了一个 QND 搜索实用程序来帮助我查找/报告我在源代码中搜索的内容。我在弄清楚我的模式搜索出了什么问题时遇到了问题,它没有返回包含两个双引号之间的所有文本的匹配字符串。在一次搜索中它有效(寻找会话变量),但在类似的搜索中(寻找重定向)它没有。

这是我正在测试的示例 aspx.vb 文件:

Partial Class _1
    Inherits System.Web.UI.Page
    Private strSecurityTest As String = ""
    Private strUserId As String = ""
    Private strPassword As String = ""
    Private strMyName As String = ""

    Private Sub sample()
        strSecurityTest = Session("UserID")

        If strSecurityTest = "NeedsLogin" Or
            strSecurityTest = "" Or
            Session("SecureCount") = 0 Or
            Session("CommandName") <> strMyName Then
            Server.Transfer("WebApLogin.aspx")
        End If
    End Sub
End Class

匹配成功:

When I look for all occurances of Session("*") with pattern ==> Session\(\"\w*\"\)
I get correct results.  Noting the above source code, I get 3 matches returned:

Session("UserID")
Session("SecureCount")
Session("CommandName")

匹配失败:

However when I try another search by replacing "Session" with "Transfer" ==> Transfer\(\"\w*\"\)
nothing is returned.  

I have also tried these matching patterns:
Server.Transfer("*") ==> Server\.Transfer\(\"\w*\"\)
*Server.Transfer("*") ==> \w*Server\.Transfer\(\"\w*\"\)

Each of these doesn't return any matches.

In my live code I tried removing vbCr, vbLf, vbCrLf before the regex match, but still no matches
were found.

症状:

A symptom that I see is when I remove the text from the right side of the pattern, up to and
including the \w* ... then the search finds matches ==> Transfer\(\"  However since the search 
is now open-ended ... I can't capture the value between the double quotes that I want.

示例 VB 代码是:

Private Sub TestRegExPattern(wData As String, wPattern As String, bMatchCase As Boolean)

    '
    ' Invoke the Match method.
    '                            
    Dim m As Match = Nothing
    If Not bMatchCase Then
        m = Regex.Match(wData, wPattern, RegexOptions.IgnoreCase)
    Else
        m = Regex.Match(wData, wPattern)
    End If

    '
    ' If first match found process and look for more
    '
    If (m.Success) Then
        '
        '   Process match
        '

        ' Get next match.
        While m.Success
            m = m.NextMatch()
            If m.Success Then
                '
                '   Process additional matches
                '
            End If
        End While
    End If
    m = nothing
End Sub

我正在寻找一些指针来理解为什么我的简单搜索只适用于一种特定的模式,而不是另一种只改变要显式匹配的前导文本的模式。

标签: regexvb.net

解决方案


推荐阅读