正则表达式模式匹配

时间:2011-08-08 13:28:09

标签: regex vb.net

我正在vb.net中开发一个正则表达式/模式测试器,我有三个文本框:

  • Textbox1:这里我在textbox2
  • 中输入模式匹配的正则表达式
  • Textbox2:从dB上传纯文本然后查找匹配
  • Textbox3:显示搜索结果。

现在我遇到的问题是当我在 Textbox1 中输入正则表达式并单击时 搜索它无法找到任何匹配的模式,即使我已确保匹配 文本出现在段落中。

但是,如果我在Textbox1中输入非正则表达词/文本本身,它就能找到匹配。

在我的按钮click_event中,我已启动所有相关的正则表达式函数等但仍然 无法弄清楚为什么除了正则表达式而不是单词本身。

以下是我用于模式搜索的代码:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  Button2.Click
    Dim m As Match
    Dim re As Regex
    Dim matches As MatchCollection

    'Clear result area
    tbResults.Text = ""

    Try
        re = New Regex(tbPattern.Text)
    Catch ex As Exception
        MsgBox("invalid regular expression")
        Exit Sub
    End Try

    If cbIgnoreCase.Checked And cbMultiline.Checked And cbSingleLine.Checked Then
        re = New Regex(tbPattern.Text, RegexOptions.IgnoreCase And RegexOptions.Multiline And RegexOptions.Singleline)
    ElseIf cbIgnoreCase.Checked And cbMultiline.Checked And (Not cbSingleLine.Checked) Then
        re = New Regex(tbPattern.Text, RegexOptions.IgnoreCase And RegexOptions.Multiline)
    ElseIf cbIgnoreCase.Checked And (Not cbMultiline.Checked) And cbSingleLine.Checked Then
        re = New Regex(tbPattern.Text, RegexOptions.IgnoreCase And RegexOptions.Multiline)
    ElseIf (Not cbIgnoreCase.Checked) And cbMultiline.Checked And cbSingleLine.Checked Then
        re = New Regex(tbPattern.Text, RegexOptions.Multiline And RegexOptions.Singleline)
    ElseIf cbIgnoreCase.Checked Then
        re = New Regex(tbPattern.Text, RegexOptions.IgnoreCase)
    ElseIf cbMultiline.Checked Then
        re = New Regex(tbPattern.Text, RegexOptions.Multiline)
    ElseIf cbSingleLine.Checked Then
        re = New Regex(tbPattern.Text, RegexOptions.Singleline)
    Else
        re = New Regex(tbPattern.Text)
    End If

    'get matches
    matches = re.Matches(tbPgCon.Text)

    'display matches found
    tbResults.Text = "Count : " & matches.Count
    For Each m In matches
        tbResults.Text = tbResults.Text & vbCrLf & "----" & vbCrLf & m.Value
    Next

    Cursor.Current = Cursors.Default

End Sub

0 个答案:

没有答案