有没有一种简单的方法来检查字符串是否以字母开头(任意 4 个字母)?

Is there an easy way to check if the string starts with letters (any 4 letters)?

有没有办法检查字符串是否以任意 4 个字母开头。我正在寻找这样的东西:

If string like "####*" then
'DO STUFF
end if

“#”用于数字,我需要同样的东西但只用于字母。 没有正则表达式可以完成吗?

我不知道不使用正则表达式的方法。我们可以尝试使用正则表达式 Test 和模式 ^[A-Z]{4}.*$:

Dim input As String
Dim regex As Object
Set regex = New RegExp

regex.Pattern = "^[A-Z]{4}.*$"
input = "ABCD blah"

If regex.Test(input) Then
    'DO STUFF
End If

您可以使用 Like 几乎与使用 RegEx 相同。

“{#}” - 在 Like 运算符中不存在,但“[A-Z]”绝对有效

if string like "[A-Z][A-Z][A-Z][A-Z]*" then
   'DO STUFF
end if

Can this be done without regEx?

是的,没有特定需要 Regular Expressions,因为 Like 运算符作为处理这种情况的某种最后手段非常有能力,就像 this 的作者一样文章解释。此外,RegEx 在较大的数据库上有点慢。尽管如此,RegEX 是一个很好用的工具!

提供的解决方案会告诉你字符串是否以4个大写字母开头。但是为了解释下限或上限,你可以扩展这个逻辑:

If str Like "[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]*" Then

然而,为了缩短这一点,我们可以使用 [!charlist] 告诉操作员我们正在寻找不在提供范围内的东西。换句话说,我们可以使用:

If str Like "[!0-9][!0-9][!0-9][!0-9]*" Then

当您的字符串包含字母数字字符以外的任何其他字符时,最后一个解决方案将不起作用。

要测试几个字符(在本例中为前 4 个字母),您始终可以执行以下操作:

If Not (Mid(string, 1, 1) Like "#" And Mid(string, 2, 1) Like "#" _ 
    And Mid(string, 3, 1) Like "#" And Mid(string, 4, 1) Like "#") Then  
    ' DO STUFF
End If

使用 Like 运算符时输入的内容会多一些,但那又怎样?另外,您可以在循环中使用 Select Case ... 另一种选择是使用 IsNumeric(Mid(string, i, 1)) 而不是 Mid(string, i, 1) Like "#",等等

诚然,这种方法对于 4 个字符仍然非常实用,但不像 RegEx 那样灵活且非常不可扩展。

使用FilterXML函数的方法

WorksheetFunction FilterXML() 已在 ►Excel 2013 中添加,并允许为给定的 XML 文档指定任何 XPath 搜索字符串,不必是本地保存的文件(需要 WebService() 函数),但可以是 格式良好 打开和关闭节点中的字符串,即我们的测试字符串与一些简单的节点添加(部分类似于 html 结构)。

调用示例[​​=41=]

Sub TextXML()
Dim myString As String
myString = "ABCD blah"
If check(myString) Then
   'DO STUFF
   Debug.Print "okay"
Else
   Debug.Print "oh no"
End If
End Sub

帮助功能

Function check(ByVal teststring As String) As Boolean
    Const s As String = Chr(185)  ' unusual character, e.g. Chr(185): "¹"
    On Error GoTo oops
    If Len(WorksheetFunction.FilterXML("<all><i>" & teststring & "</i></all>", "//i[substring(translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','" & _
       String(26, s) & "'),1,4)='" & String(4, s) & "']")) > 0 Then check = True
    Exit Function
oops:
    Err.Clear
End Function

tl;tr - 如何在 2013

之前的 Excel 版本中使用 VBA

为了艺术的缘故,通过 XMLDOM 方法使用 XPath 的经典方法:

调用示例[​​=41=]

Sub TextXML2()
Dim myString As String
myString = "ABCD blah"

If check2(myString) Then
   'DO STUFF
   Debug.Print "okay"
Else
   Debug.Print "oh no"
End If
End Sub

帮助功能

Function check2(ByVal teststring As String) As Boolean
' Purpose: check if first 4 characters of a test string are upper case letters A-Z
  ' [0] late bind XML document
    Dim xDoc As Object
    Set xDoc = CreateObject("MSXML2.DOMDocument.6.0")
  ' [1] form XML string by adding opening and closing node names ("tags")
    teststring = "<all><i>" & teststring & "</i></all>"
  ' [2] load XML
    If xDoc.LoadXML(teststring) Then
      ' [3a] list matching item(s) via XPath
        Dim myNodeList As Object
        Set myNodeList = xDoc.SelectNodes(XPath())
            'Debug.Print teststring, " found: " & myNodeList.Length
      ' [3b] return true if the item matches, i.e. the list length is greater than zero
        If myNodeList.Length > 0 Then check2 = True
    End If

End Function

Function XPath() As String
' Purpose: create XPath string to get nodes where the first 4 characters are upper case letters A-Z
' Result: //i[substring(translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹¹'),1,4)="¹¹¹¹"]
  ' get UPPER case alphabet
    Const ABC     As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  ' define replacement string consisting of an unusual character repeated 26 times
    Const UNUSUAL As String = "¹"       ' << replace by your preferenced character
    Dim replacement As String: replacement = String(Len(ABC), UNUSUAL)
    'return XPath string
    XPath = "//i[substring(translate(.,'" & ABC & "','" & replacement & "'),1,4)=""" & String(4, UNUSUAL) & """]"
End Function