screenshot我需要从单个单元格中提取三个变量。我已经能够使用正则表达式提取前4个数字。现在我还想提取接下来的四位数字(1970)我需要添加什么来获得它?
截图:
Function getZip(addr As String)
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = "(\d{4})"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(addr)
If (allMatches.Count <> 0) Then
result = allMatches.Item(0).submatches.Item(0)
End If
getZip = result
End Function
答案 0 :(得分:1)
我只想添加3个模式和一个参数PatternNo
来选择使用哪种模式:
Function getZip(addr As String, PatternNo As Long)
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
Dim Patterns As Variant 'define 3 patterns 0 to 2
Patterns = Array("([0-9]{4}) .*", "[0-9]{4} (.*)", "bygget i ([0-9]{4})")
'you might want to add an error handling here (see end of this answer)
RE.Pattern = Patterns(PatternNo) 'choose pattern by its number
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(addr)
If (allMatches.Count <> 0) Then
result = allMatches.Item(0).submatches.Item(0)
End If
getZip = result
End Function
我建议这些模式:
([0-9]{4}) .*
https://regex101.com/r/zm6Tzz/1 [0-9]{4} (.*)
https://regex101.com/r/GLqRMH/1 bygget i ([0-9]{4})
https://regex101.com/r/6sp4M8/1 最好检查PatternNo
是否不超过数组Patterns
中的模式数,如果出现错误则返回错误:
If PatternNo < 0 Or PatternNo > UBound(Patterns) Then
getZip = 'return your desired error here
Exit Function
End If
如果根本找不到匹配项,您可能还想要返回错误。