|
楼主 |
发表于 2024-4-18 10:13
|
显示全部楼层
本帖最后由 ning84 于 2024-4-18 10:46 编辑
学习正则方法近十年,还是一知半解。
笨办法学习,一遍一遍做题。
- Sub ll()
- Dim Arr(3)
- Arr(0) = "IMG20231121102939.jpg"
- Arr(1) = "IMG_20231121_100743630.jpg"
- Arr(2) = "IMG_20231121_101338692.jpg"
- Arr(3) = ".Screenshot_2024-01-18-06-15-33-976_com.autonavi.minimap.jpg"
- Dim RegArr(2)
- RegArr(0) = "([\d]{2,4})([\d]{1,2})([\d]{1,2})_([\d]{1,2})([\d]{1,2})([\d]{1,2})"
- RegArr(1) = "([\d]{2,4})-([\d]{1,2})-([\d]{1,2})-([\d]{1,2})-([\d]{1,2})-([\d]{1,2})"
- RegArr(2) = "([\d]{2,4})([\d]{1,2})([\d]{1,2})([\d]{1,2})([\d]{1,2})([\d]{1,2})"
- Dim Str
- For ii = 0 To UBound(RegArr)
- For jj = 0 To UBound(Arr)
- Str = RegYYYYMMDDHMS(RegArr(ii), Arr(jj))
- If IsDate(Str) Then
- Debug.Print Arr(jj), Str
- End If
- Next jj
- Next ii
-
-
- End Sub
- Function RegYYYYMMDDHMS(RegStr, oStr)
- Dim Str
- Dim oRegExp As RegExp 'VB使用正则表达式匹配模式的主要对象
- Set oRegExp = New RegExp
- Dim oMatColl As MatchCollection '是集合对象,包含有关匹配字符串的信息,该对象包含每个成功匹配的 Match 对象
- Dim oMatch As Match '成功匹配的对象
- 'Dim oSubMat As SubMatches '匹配对象所匹配结果的子项
- Dim oDate As Date
- '''
- oRegExp.Pattern = RegStr
- Set oMatColl = oRegExp.Execute(oStr)
- If oMatColl.Count = 0 Then
- RegYYYYMMDDHMS = oStr
- Exit Function
- End If
- Set oMatch = oMatColl.Item(0)
- With oMatch.SubMatches
- Str = .Item(0) & "/" & .Item(1) & "/" & .Item(2)
- Str = Str & " " & .Item(3) & ":" & .Item(4) & ":" & .Item(5)
- End With
- If IsDate(Str) Then
- oDate = Str
- RegYYYYMMDDHMS = oDate
- End If
-
-
- End Function
复制代码
''''
- Function RegYYYYMMDDHMS(oStr)
- Dim RegArr(2)
- RegArr(0) = "([\d]{2,4})([\d]{1,2})([\d]{1,2})_([\d]{1,2})([\d]{1,2})([\d]{1,2})"
- RegArr(1) = "([\d]{2,4})-([\d]{1,2})-([\d]{1,2})-([\d]{1,2})-([\d]{1,2})-([\d]{1,2})"
- RegArr(2) = "([\d]{2,4})([\d]{1,2})([\d]{1,2})([\d]{1,2})([\d]{1,2})([\d]{1,2})"
- Dim Str
- Dim oRegExp As RegExp 'VB使用正则表达式匹配模式的主要对象
- Set oRegExp = New RegExp
- Dim oMatColl As MatchCollection '是集合对象,包含有关匹配字符串的信息,该对象包含每个成功匹配的 Match 对象
- Dim oMatch As Match '成功匹配的对象
- 'Dim oSubMat As SubMatches '匹配对象所匹配结果的子项
- Dim oDate As Date
- '''
- For ii = 0 To UBound(RegArr)
- oRegExp.Pattern = RegArr(ii)
- Set oMatColl = oRegExp.Execute(oStr)
- If oMatColl.Count > 0 Then
- Exit For
- End If
- Next ii
- If oMatColl.Count = 0 Then
- RegYYYYMMDDHMS = oStr
- Exit Function
- End If
- Set oMatch = oMatColl.Item(0)
- With oMatch.SubMatches
- Str = .Item(0) & "/" & .Item(1) & "/" & .Item(2)
- Str = Str & " " & .Item(3) & ":" & .Item(4) & ":" & .Item(5)
- End With
- If IsDate(Str) Then
- oDate = Str
- RegYYYYMMDDHMS = oDate
- End If
-
-
- End Function
- Sub ll()
- Dim Sht As Worksheet
- Dim Rng As Range
- Set Rng = Selection.CurrentRegion
- Set Sht = Rng.Parent
- With Sht
- Set Rng = .Cells(Rng.Row, "B").Resize(Rng.Rows.Count)
- End With
- 'Debug.Print Rng.Address
-
- For ii = 1 To Rng.Rows.Count
- Rng(ii, 4) = RegYYYYMMDDHMS(Rng(ii, 1))
- Next ii
-
- End Sub
复制代码 |
|