我正在尝试编写一个函数,该函数接受一个字符串,对其进行解析,然后返回另一个字符串,该字符串总结了原始字符串中连续字母或数字字符的数量。
例如,字符串999aa45bbx
将返回3N2A2N3A
,即
- 3个数字,
- 其次是 2 个阿尔法,
- 由2个数字,
- 3 阿尔法。
我正在使用该功能来分析保险单 ID 号的格式。到目前为止,我在网上找到了提取字母或数字字符的解决方案,但没有描述这些字符在原始字符串中存在的格式或顺序。
任何人都可以帮忙吗?
像这样的正则表达式将完成这项工作
那么您可以在 Excel 中使用该函数(它也检测无效字符串),即在 B1 中
=AlphaNumeric(A1)
Function AlphaNumeric(strIn As String) As String
Dim objRegex As Object
Dim objRegMC As Object
Dim objRegM As Object
Dim strOut As String
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.ignorecase = True
.Pattern = "[^\w]"
If .test(strIn) Then
AlphaNumeric = "One or more characters is invalid"
Else
.Pattern = "(\d+|[a-z]+)"
Set objRegMC = .Execute(strIn)
For Each objRegM In objRegMC
strOut = strOut & (objRegM.Length & IIf(IsNumeric(objRegM), "N", "A"))
Next
AlphaNumeric = strOut
End If
End With
End Function
老派,遍历字符串中的所有字符:
Function IdentifyCharacterSequences(s As String) As String
Dim i As Long
Dim charCounter As Long
Dim currentCharType As String
Dim sOut As String
sOut = ""
charCounter = 1
currentCharType = CharType(Mid(s, 1, 1))
For i = 2 To Len(s)
If (Not CharType(Mid(s, i, 1)) = currentCharType) Or (i = Len(s)) Then
sOut = sOut & charCounter & currentCharType
currentCharType = CharType(Mid(s, i, 1))
charCounter = 1
Else
charCounter = charCounter + 1
End If
Next i
IdentifyCharacterSequences = sOut
End Function
这使用以下辅助函数。请注意,非字母数字字符使用字母“X”标识。您可以轻松修改它以适合您的目的。
Function CharType(s As String) As String
If s Like "[A-z]" Then
CharType = "A"
ElseIf s Like "[0-9]" Then
CharType = "N"
Else
CharType = "X"
'Or raise an error if non-alphanumerical chars are unacceptable.
End If
End Function
使用示例: