'批注: 贪婪懒惰占有模式
'1 ?Greedy 贪婪但回溯
' * + ? {n,m}
' 尝试匹配尽量多的字符,但如果后面的正则无法匹配成功,它会吐出字符,尝试让后面的正则匹配
'2 ?Lazy 懒惰
' *? +? ?? {n,m}?
' 匹配尽可能少的字符,匹配后,如果后面的正则无法匹配成功,它会向前吃字符(回溯进食),尝试让后面的模式匹配成功
'3 ?Possessive 霸道占有
' 尝试匹配尽量多的字符,且坚决不回吐
' *+ ++ ?+ {n,m}+
' ============================================================================
' Test 1: 贪婪 vs 懒惰
' ============================================================================
Public Sub Test09_GreedyVsLazy()
Debug.Print "========== Test 1: 贪婪 vs 懒惰 =========="
Dim re As Object
Set re = CreateObject("loquat.RegExp")
Dim text As String
text = "<div>content1</div><div>content2</div>"
' 贪婪匹配
re.Pattern = "<div>.*</div>"
Debug.Print " Greedy match '<div>.*</div>':"
Dim match As Object
Set match = re.Execute(text)
If match.Count > 0 Then
Debug.Print " Match: " & match(0).Value
End If
' 懒惰匹配
re.Pattern = "<div>.*?</div>"
Debug.Print " Lazy match '<div>.*?</div>':"
Set match = re.Execute(text)
Dim i As Long
For i = 0 To match.Count - 1
Debug.Print " Match " & (i + 1) & ": " & match(i).Value
Next i
Debug.Print ""
End Sub
' ============================================================================
' Test 2: 占有模式
' ============================================================================
Public Sub Test10_PossessiveQuantifiers()
Debug.Print "========== Test 2: 占有模式 =========="
Dim re As Object
Set re = CreateObject("loquat.RegExp")
' 占有模式(不回溯)
re.Pattern = "\d++\."
Debug.Print " 占有模式(不回溯) '\d++\.' on '123.456':"
Dim match As Object
Set match = re.Execute("123.456")
If match.Count > 0 Then
Debug.Print " Match: " & match(0).Value
Else
Debug.Print " No match (possessive quantifier prevents backtracking)"
End If
' 普通贪婪(回溯)
re.Pattern = "\d+\."
Debug.Print " 普通贪婪(回溯) '\d+\.' on '123.456':"
Set match = re.Execute("123.456")
If match.Count > 0 Then
Debug.Print " Match: " & match(0).Value
End If
Debug.Print ""
End SubCopyright © 2025- vba.vip All Rights Reserved.