How to lazily backtrack for regex match?

Viewed 43

Consider the following strings:

Wohnfläche angeblich: ca. 140 m²
Wohn/Nutzfläche ca. 211 m², renovie
Ca. 1111 gebautes und ab 222 umgebautes, etc , etc, ca. 144 m²
Ca. 71 m² große, etc (etc. ca. 1234) 

In each case I want to extract the m² value i.e. 140, 211, 144, 71 using a regex pattern that applies to VBA.

The problem I am having is that I cannot find the right regex pattern to lazily backtrack (apologies if wrong terminology) to only get the shortest match i.e. the numbers immediately preceding the m² and following the Ca.|ca.

I am currently trying:

ca\.\s(.*?)\s(?=m²)

with flags|settings: multiline False, global False and ignoreCase True.

The third case is matching too long a string:

Ca. 1111 gebautes und ab 222 umgebautes, etc , etc, ca. 144

Instead of:

ca. 144

Given the limitations of VBA in terms of lookarounds is there a way to get just the desired value?

E.g. failure:

Option Explicit

Public Sub test()

    Dim re As Object
    
    Set re = CreateObject("VBScript.RegExp")
    
    With re
        .Global = False
        .MultiLine = False
        .IgnoreCase = True
        .Pattern = "ca\.\s(.*?)\s(?=m²)"
    End With
    
    Debug.Print re.Execute("Ca. 1111 gebautes und ab 222 umgebautes, etc , etc, ca. 144 m²")(0).submatches(0)
      
End Sub

The temporary workaround is not specific enough as it ignores the ca.|Ca. requirement with "\s([0-9.]+)\sm²"

1 Answers

You can use

ca\.\s*(\d+(?:[.,]\d+)*)\s*m²

See the regex demo.

Details

  • ca\. - ca. string
  • \s* - zero or more whitespaces
  • (\d+(?:[.,]\d+)*) - Group 1: one or more digits and then zero or more repetitions of . or , and one or more digits
  • \s* - zero or more whitespaces
  • - a text.
Related