我正在循环使用这种模式name_name-number-name_name.txt
我需要提取number
。
例如,
xxx_xx-111-ssadas22
我会得到111
。xxx_xx-11-sadaesdwsq4443fsd2
我会得到11
目前正在使用此功能,但如果名称中有数字,则不足。还尝试了一个正则表达式但是很糟糕。
Function FirstDigit(strData As String) As Integer
Dim RE As Object
Dim REMatches As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Pattern = "(^|\\s)([0-100]+)($|\\s)"
End With
Set REMatches = RE.Execute(strData)
FirstDigit = REMatches.item(0)
End Function
任何想法?
答案 0 :(得分:1)
试试这个:
Function FirstDigit(strData As String) As Integer
Dim RE As Object
Dim REMatches As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Pattern = "\b[^_\s]+_[^-\s]+-(\d+)-[^\.\s]+\.txt\b"
End With
Set REMatches = RE.Execute(strData)
If REMatches.Count > 0 Then
FirstDigit = REMatches(0).SubMatches(0)
Else
FirstDigit = -1 '' or whatever you want to output when there is no match
End If
End Function
测试:
Sub Test()
Debug.Print FirstDigit("xxx_xx-1-ssadas22.txt") '' Returns 1
Debug.Print FirstDigit("xxx_xx-11-ssadas22.txt") '' Returns 11
Debug.Print FirstDigit("xxx_xx-111-ssadas22.txt") '' Returns 111
Debug.Print FirstDigit("xxx_xx-asasa-ssadas22.txt") '' Returns -1 (no match)
End Sub
答案 1 :(得分:0)
怎么样:
Function FirstDigit(strData As String) As Integer
FirstDigit = 0
ary = Split(strData, "-")
For i = LBound(ary) To UBound(ary)
If IsNumeric(ary(i)) Then
FirstDigit = CInt(ary(i))
Exit Function
End If
Next i
End Function
答案 2 :(得分:0)
如果字符串的模式保持不变,那么这对我有用
Sub Sample()
Debug.Print FirstDigit("xxx_xx-1-ssadas22")
Debug.Print FirstDigit("xxx_xx-11-ssadas22")
Debug.Print FirstDigit("xxx_xx-111-ssadas22")
End Sub
Function FirstDigit(strData As String) As Integer
Dim RE As Object
Dim REMatches As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Pattern = "(\-([^-]+)\-)"
End With
Set REMatches = RE.Execute(strData)
FirstDigit = Abs(Val(REMatches.Item(0)))
End Function
答案 3 :(得分:0)
这有效,并且不要求您的文件名适合任何特定模式。对于任何输入字符串,它将返回第一个(整个)数字,即连续数字字符的第一个序列。
Function GetFirstNumber(s As String) As String
Dim i As Long
Dim strFirstNumber As String
Dim thisChar As String
Dim foundNumberStart As Boolean
For i = 1 To Len(s)
thisChar = Mid(s, i, 1)
If thisChar Like "[0-9]" Then
foundNumberStart = True
strFirstNumber = strFirstNumber & thisChar
ElseIf foundNumberStart Then
Exit For 'Number finished.
End If
Next i
GetFirstNumber = strFirstNumber
End Function
使用示例:
?GetFirstNumber(" xxx_xx-111-ssadas22")
111
?GetFirstNumber("xxx_xx-11-sadaesdwsq4443fsd2")
11
?GetFirstNumber(" kjhsdfg WWWAAHHH!*666zombiesarecoming9827365498#%")
666