这是第一次破解,可能有更好的方法,正则表达式不是我的事,但它适用于示例:
Public Function ValString(strInput As String) As String
Static regEx As Object
Dim x As Long
Dim temp$
Dim matches As Object
If regEx Is Nothing Then Set regEx = CreateObject("vbscript.regexp")
With regEx
.Pattern = "^AB([0-9]{2})([A-Za-z]{" & Val(Mid(strInput, InStr(1, strInput, "AB") + 2, 2)) & "})CD([0-9]{2})([A-Za-z]{" & Val(Mid(strInput, InStr(1, strInput, "CD") + 2, 2)) & "})(OP([0-9]{2})[A-Za-z]+EF[0-9]+|EF[0-9]+)$"
Set matches = .Execute(strInput)
If .Test(strInput) Then
ValString = "Validation Success"
Exit Function
Else
.Pattern = "(AB|CD|EF)"
.Global = True
Set matches = .Execute(strInput)
If matches.Count > 0 Then
temp$ = "ABCDEF"
For x = 0 To matches.Count - 1
temp$ = Replace(temp$, matches(x), vbNullString)
ValString = ValString & ",'" & matches(x) & "'"
Next x
If Len(temp$) > 1 Then
ValString = "Error:Expected '" & temp$ & "', Found " & Right(ValString, Len(ValString) - 1)
Else
ValString = "Error:Paramaters Found, invalid string"
End If
Else
ValString = "Error:Expected 'CD', Found nothing"
End If
End If
End With
End Function
根据 Chris 的建议,经过编辑以强制 AB 和 CD 后面的 2 位数字指示以下字符的长度
如果 Characters OP 遵循相同的模式,那么您可以使用:
.Pattern = "^AB([0-9]{2})([A-Za-z]{" & Val(Mid(strInput, InStr(1, strInput, "AB") + 2, 2)) & "})CD([0-9]{2})([A-Za-z]{" & Val(Mid(strInput, InStr(1, strInput, "CD") + 2, 2)) & "})(OP([0-9]{2})([A-Za-z]{" & Val(Mid(strInput, InStr(1, strInput, "OP") + 2, 2)) & "})EF[0-9]+|EF[0-9]+)$"
如上所述,但 EF 也遵循相同的模式,但仅适用于数字:
.Pattern = "^AB([0-9]{2})([A-Za-z]{" & Val(Mid(strInput, InStr(1, strInput, "AB") + 2, 2)) & "})CD([0-9]{2})([A-Za-z]{" & Val(Mid(strInput, InStr(1, strInput, "CD") + 2, 2)) & "})(OP([0-9]{2})([A-Za-z]{" & Val(Mid(strInput, InStr(1, strInput, "OP") + 2, 2)) & "})(EF[0-9]{2})([0-9]{" & Val(Mid(strInput, InStr(1, strInput, "EF") + 2, 2)) & "})|(EF[0-9]{2})([0-9]{" & Val(Mid(strInput, InStr(1, strInput, "EF") + 2, 2)) & "}))$"