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

时间:2019-12-23 08:15:34

标签: excel vba string letter

是否可以检查字符串是否以任何4个字母开头。我正在寻找这样的东西:

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

“#”用于数字,我需要同样的东西,但仅用于字母。 不用regEx可以做到吗?

5 个答案:

答案 0 :(得分:4)

我不知道不使用正则表达式的方法。我们可以尝试将正则表达式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

答案 1 :(得分:3)

您可以使用Like进行此操作,几乎可以使用RegEx。

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

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

答案 2 :(得分:3)

  

可以不用regEx吗?

是的,Regular Expressions并没有特别的需要,因为Like运算符完全有能力来处理这种情况,就像this文章的作者所解释的那样。而且,RegEx在较大的数据库上有点慢。尽管如此,RegEX是一个很棒的工具!

@AlexandruHapco提供的解决方案将告诉您字符串是否以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

当您的字符串中包含字母数字字符以外的其他任何字符时,后一种解决方案将无效。

答案 3 :(得分:1)

使用FilterXML函数的方法

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

示例呼叫

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的经典方法是:

示例呼叫

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

答案 4 :(得分:0)

要测试几个字符(在这种情况下为前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那样灵活且几乎不可扩展。

相关问题