簡體   English   中英

VB.Net正則表達式幫助

[英]VB.Net Regex Help

我有3或4種模式,可以將用戶輸入與之進行比較,我需要弄清楚用戶輸入是否與模式之一匹配,如果匹配則返回匹配。

由於輸入是多行的,所以我像這樣傳遞每行:

    Dim strRawInput() As String = Split(txtInput.Text, vbCrLf)
    Dim strInput As String

    txtOutput.Text = ""

    For Each strInput In strRawInput
        strInput.Trim(vbCr, vbLf, Chr(32))
        Validation(strInput)
    Next

然后我有這個來找到匹配項:

Dim m As Match

For i = 0 To strValidator.Length - 1
    Dim r As New Regex(strValidator(i))
    m = r.Match(strInput)

    If m.Success Then
        txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
        Exit Sub 
    Else

    End If
Next
txtOutput.Text = txtOutput.Text & "Not this time" & vbCrLf

我怎樣才能更有效地做到這一點? 另外,我在此處添加了Exit Sub,以避免即使找到匹配項后仍顯示“ Not this time”消息(如果匹配項與數組中的更高版本之一),但我想找到一種更好的方法也這樣做。

提前致謝。

而不是在循環中生成正則表達式,而是在應用程序啟動時一次生成它們。 所以也許是這樣的:

Private Shared m_regexes As New List(Of Regex)
Shared Sub New()
    For Each v As String In strValidator
        m_regexes.Add(New Regex(v))
    Next
End Sub

然后,您可以將其他代碼更改為:

For Each r As Regex In m_regexes
    Dim m As Match = r.Match(strInput)
    If m.Success Then
        txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
        Exit Sub
    Else

    End If
Next

關於Exit Sub ,我認為很好,您已經發現它至少匹配一種模式,為什么還要繼續評估其余模式。 但是,如果您不喜歡可以在多個位置“返回”的方法,則可以將其替換為BooleanExit For

Dim found as Boolean = false 
For Each ...
     If IsMatch Then
          found = True
          Exit For
     End If
 Next

 If Found Then
       ....
 Else
       .....
 End If

嗯,如果是這樣,那會更好嗎?

For i = 0 To strValidator.Length - 1
    Dim r As New Regex(strValidator(i))
    Dim m As Match = r.Match(strInput)

    If m.Success Then
        txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
        Exit Sub 
    End If
Next

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM