Finding terms with missing opening brackets in a string

Viewed 96

In a string, I need to find the terms which contain missing opening brackets e.g. hi], hi}, hi)

I am able to find terms with a missing closing bracket in a string as shown below:

import re
missing_close = re.compile(r'(\w+|\s)?(\(|\[|\{)(\w+|\s)?[^\]})](\\|\s|\.)')
sen = "It is (fine [day]"
res_close = missing_close.finditer(sen)
for i in res_close:
    print(i.group(0))

Output:

(fine

When a similar regex to find missing opening brackets,

   missing_open = re.compile(r'(\\|\s|\.|\,)?[^\([{](\w+|\s)?(\)|\}|\])(\s|\.|\\)?')
   sen = "It is} [fine] day"
   res_open = missing_open.finditer(sen)
   for i in res_open:
       print(i.group(0))

Getting output with all terms having brackets

Output:

 is} 
fine]

Only is} is the needed output

1 Answers

You can use

import re
missing_close = re.compile(r'\([^()]*\)|\[[^][]*]|\{[^{}]*}|(\w+[])}]|[([{]\w+)')
sen = "It is (fine [day]"
res_close = missing_close.finditer(sen)
for i in res_close:
    if i.group(1):
        print(i.group(1))

See the Python demo and the regex demo. The point is to match strings between closest ( and ), [ and ], and { and }, and capture the words starting with {, [ or ( or words ending with ), } or ], and only return Group 1 values.

Regex details:

  • \([^()]*\)|\[[^][]*]|\{[^{}]*} - strings between ( and ), [ and ] or { and } with no corresponding brackets inside
  • | - or
  • (\w+[])}]|[([{]\w+) - Group 1:
    • \w+[])}] - one or more word chars and then ], ) or }
    • | - or
    • [([{]\w+ - (, [ or { and one or more word chars.
Related