简体   繁体   English

VB.Net正则表达式帮助

[英]VB.Net Regex Help

I've got 3 or 4 patterns that I'm comparing user input against and I need to figure out if the user input matches one of the patters and to return the match if it does. 我有3或4种模式,可以将用户输入与之进行比较,我需要弄清楚用户输入是否与模式之一匹配,如果匹配则返回匹配。

Since the input is multiline, I'm passing each individual line like so: 由于输入是多行的,所以我像这样传递每行:

    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

Then I have this to find matches: 然后我有这个来找到匹配项:

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

How can I do this more efficiently? 我怎样才能更有效地做到这一点? Also, I added the Exit Sub there to avoid showing the "Not this time" message even after a match is found (if the match is with one of the later patterns in the array), but I'd like to find a better way of doing that too. 另外,我在此处添加了Exit Sub,以避免即使找到匹配项后仍显示“ Not this time”消息(如果匹配项与数组中的更高版本之一),但我想找到一种更好的方法也这样做。

Thanks in advance. 提前致谢。

Rather than generating your Regexs in the loop, generate them one time at the startup of the application. 而不是在循环中生成正则表达式,而是在应用程序启动时一次生成它们。 So maybe something like: 所以也许是这样的:

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

And then you can change your other code to: 然后,您可以将其他代码更改为:

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

Regarding the Exit Sub , I think it's fine, You've discovered that it matches at least one pattern, so why continue to evaluate the rest. 关于Exit Sub ,我认为很好,您已经发现它至少匹配一种模式,为什么还要继续评估其余模式。 But if you don't like methods that can "return" in multiple places, you could just replace it with a Boolean and a Exit For as: 但是,如果您不喜欢可以在多个位置“返回”的方法,则可以将其替换为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

Hmm if that's the case then wouldn't this be even better? 嗯,如果是这样,那会更好吗?

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