Detecting a line with open curly brackets

Viewed 267

I am parsing a tcl file line line by line and searching for lines with open curly braces so that I can merge them with the next line and read them. I am struggling to get a single regex to do this. My concern is lines with with a closing } which can be skipped.

Example: MATCH: test_command -switch1 {

NO MATCH: single_command

NO MATCH: test_tcl -switch2 {arg1 }

Please help with the regex to get the result. I tried this:

% set a "test_command -swithc1 {bye }"
test_command -swithc1 {bye }
% regexp "{" $a match
1
#0 is expected

This is not my intention. I want match only for lines with open curly brace

% set b "test_command -swithc1 {hi"
test_command -swithc1 {hi
% regexp "{" $a match
1
#1 was expected

I'm looking for a regex that will give 0 for the $a and 1 for $b

2 Answers

You really shouldn't be using a regular expression for that; there's a Tcl command specifically for this sort of thing: info complete. Here's how to use it:

set accumulator ""
while {![eof $inputChannel]} {
    # Note well: you *must* add the newline
    append accumulator [gets $inputChannel] "\n"
    if {[info complete $accumulator]} {
        handleCompleteChunk $accumulator
        set accumulator ""
    }
}

This handles various types of bracket matching and the intricacies of backslash sequences, but just to check whether the “line” is complete. (It's also the core of how Tcl's REPL works, except that uses the Tcl C API equivalents.)

You could try a couple "lookarounds", one to say "I see a left bracket" and one to say "I don't see a right bracket":

(?!.*\})(?=.*\{)

https://regex101.com/r/p8bbsF/1/

Related