将字符串分解为单个元素并测试字符类型 - NUM - LETTER - SPECIAL - Excel VBA

问题描述 投票:0回答:2

我需要弄清楚如何测试字符串中的每个字符以查看它是否是数字/字母/特殊字符。

我的问题是,如何打破字符串并测试每个角色,看看角色是否是number/letter/special character

例如:

var = 1S@

Result1 = Num
Result2 = Alpha
Result3 = Special
regex excel vba
2个回答
0
投票

如果你的意思是

转义将被视为正则表达式中的文字字符串的用户输入 - 否则将被误认为是特殊字符。

然后你可以用给定的正则表达式替换它:

/[.*+?^${}()|[\]\\]/g

0
投票

所以我通过在SO上结合几个不同的帖子来实现它。此代码中断了数组中的字符串,然后检查每个字符串中的num / alpha / special,并为*提供了一个特殊情况。

-

Sub test()

'''Special Character Section'''
Dim special_charArr() As String
Dim special_char As String

special_char = "!,@,#,$,%,^,&,*,+,/,\,;,:"
special_charArr() = Split(special_char, ",")
'''Special Character Section'''

'''Alpha Section'''
Dim regexp As Object
Set regexp = CreateObject("vbscript.regexp")

Dim strPattern As String
strPattern = "([a-z])"

With regexp
    .ignoreCase = True
    .Pattern = strPattern
End With
'''Alpha Section'''

Dim buff() As String
my_string = "t3s!*"
ReDim buff(Len(my_string) - 1)
For i = 1 To Len(my_string)
    buff(i - 1) = Mid$(my_string, i, 1)
    char = buff(i - 1)
    If IsNumeric(char) = True Then
        MsgBox char & " = Number"
    End If
    For Each Key In special_charArr
     special = InStr(char, Key)
      If special = 1 Then
        If Key <> "*" Then
            MsgBox char & " = Special NOT *"
        Else
            MsgBox char & " = *"
        End If
      End If
    Next
    If regexp.test(char) Then
        MsgBox char & " = Alpha"
    End If
Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.