我有一个字符串列表,其中在遇到前三位数字之前在开头包含几组字符和空格。 如果找到模式,那么我只需要收集字符串中的前三位数字。
例如1: 字符串:“SEE 222 纽卡斯尔新南威尔士州 203” 预期产量:222
例如2: 字符串:“SEE TEMP 212 纽卡斯尔新南威尔士州 203” 预期产量:212
请推荐
Sub TestExtractFirstThreeDigits()
Dim testString1 As String
Dim testString2 As String
Dim result As String
testString1 = "SEE 222 Newcastle NSW 203"
testString2 = "SEE TEMP 212 Newcastle NSW 203"
result = ExtractFirstThreeDigits(testString1)
Debug.Print "Example 1: " & result ' Expected output: 222
result = ExtractFirstThreeDigits(testString2)
Debug.Print "Example 2: " & result ' Expected output: 212
End Sub
Function ExtractFirstThreeDigits(inputString As String) As String
Dim regex As Object
Dim matches As Object
Dim firstThreeDigits As String
' Create the RegExp object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Pattern = "\b\d{3}\b" ' Pattern to match exactly three digits
.Global = False ' We only need the first match
End With
' Execute the regex search
Set matches = regex.Execute(inputString)
' Check if any match is found
If matches.Count > 0 Then
firstThreeDigits = matches(0).Value
Else
firstThreeDigits = ""
End If
' Return the first three digits found
ExtractFirstThreeDigits = firstThreeDigits
End Function