Regular expression for Word wildcard search to find parentheses including at least 3 consecutive digits

136 Views Asked by At

In the following example:

airspeed (AS) user (104A, 104B) device (101) vehicles (105A-C)

the search should find (104A, 104B), (101), and (105A-C) but not (AS).

I tried using [\(]*[0-9][0-9][0-9]*[\)] but that found everything from the (AS) to the (105A-C).

3

There are 3 best solutions below

0
Oscar  Sun On BEST ANSWER

How about this:

 [(][0-9][0-9][0-9]*[)]

[\(][0-9][0-9][0-9]*[\)]

or

[(]([0-9]{3,})*[)]

This is not a Regular expression Just a wildcard search. This "Find and Replace" dialog box does not support the Regular expression.

0
Golden Lion On

try using a capture group .*? which is non greedy

data="airspeed (AS) user (104A, 104B) device (101) vehicles (105A-C)"

regex = re.compile(r'\((\d{3}.*?)\)')
matches = regex.finditer(data)
output = []
for match in matches:
    output.append(match.group(0))
print(output)
0
Oscar  Sun On

As far as I know, regular expressions cannot be used in MS Word's search(Find-Replace-Go) box, and the only way to use them in Word is to write programs in VBA to apply them.

If you are still interested in writing regular expressions to achieve this project, you can try to run the following code in the VBE. It will find all the text in the active document that matches the criteria and mark them in red (change them to red). The criteria are as you specified: it is the range of text with at least 3 digits inside the parentheses.

Sub RegExFind_MarkRed_3digits_in_parentheses()

    Dim text2Found As String, d As Document, ur As UndoRecord
    Set ur = Word.Application.UndoRecord
    ur.StartCustomRecord "RegExFind_MarkRed_3digits_in_parentheses"
    
    Set d = ActiveDocument
    text2Found = d.Content.Text
    
    'Dim re As New VBScript_RegExp_10.RegExp, matches As VBScript_RegExp_10.MatchCollection, match As VBScript_RegExp_10.match
    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp") 'https://learn.microsoft.com/en-us/dotnet/standard/base-types/the-regular-expression-object-model
                                                'https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference
                                                'https://www.regular-expressions.info/vbscript.html

    Dim matches As Object 'As MatchCollection
    Dim match As Object 'As match

    regEx.Pattern = "\([^)]*?\d{3}[^)]*?\)"
    
    regEx.Global = True

    ' Executive Search
    Set matches = regEx.Execute(text2Found)

    ' Show matching results
    For Each match In matches
        'Debug.Print match.Value
        d.Range(match.FirstIndex + 2, match.FirstIndex + match.Length + 2).Font.ColorIndex = wdRed
    Next
    
    ur.EndCustomRecord

End Sub