[英]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
,我认为很好,您已经发现它至少匹配一种模式,为什么还要继续评估其余模式。 但是,如果您不喜欢可以在多个位置“返回”的方法,则可以将其替换为Boolean
和Exit 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.