测试字符串格式

时间:2018-12-02 23:30:41

标签: excel vba

如何测试字符串的格式是否以“ R”开头,后接最多8个数字?

2 个答案:

答案 0 :(得分:2)

使用正则表达式很容易做到这一点。

Function testString(ByVal tstStr As String) As Boolean

    With CreateObject("VBScript.RegExp")
        .Pattern = "^R\d{0,8}$"
        .IgnoreCase = False
        testString = .test(tstStr)
    End With

End Function
如果.test()与您的tstStr相匹配,

.Pattern返回一个布尔值。

打破模式^R\d{0,8}$

  • ^字符串的开头
  • R与文字R匹配
    • 如果您还可以匹配小写字母r,则可以设置IgnoreCase = True
  • \d与数字匹配0-8次{0,8}
  • $匹配字符串的结尾

由于这是一个函数,因此您可以测试任何输入字符串

Debug.Print testString("R123456")
Rem: Prints 'True'

答案 1 :(得分:1)

请参阅https://theburningmonk.com/2012/05/performance-test-string-contains-vs-string-indexof-vs-regex-ismatch/,了解RegEx为什么不是执行简单任务的最佳选择。

Str = "R12345678"
If Left(Str,1) = "R" then 
    if IsNumeric(Mid(Str, 2)) then 
        MsgBox "Match"
    End If
End If
相关问题