bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: succinct awk code to check for paired parantheses?


From: Manuel Collado
Subject: Re: succinct awk code to check for paired parantheses?
Date: Wed, 24 Mar 2021 22:35:29 +0100
User-agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.5.0

El 24/03/2021 a las 14:32, Peng Yu escribió:

I want to check whether parentheses (only "()") in a string are all
paired. Here is some awk code. But it looks quite clumsy. Is there a
better implementation more readable and succinct? Thanks.

https://stackoverflow.com/questions/2667494/awk-brackets-checking

$ cat paired.awk
# Check well-formed parentheses ()[]{}

function paired(text) {
    while (gsub(/\([^()[\]{}]*\)/,"",text) \
        +  gsub(/\[[^()[\]{}]*\]/,"",text) \
        +  gsub(/\{[^()[\]{}]*\}/,"",text) \
    ) {}  # just replace pairs
    return text !~ /[()[\]{}]/
}
{ print paired($0) }

$ gawk -f paired.awk
ab(cd)ef
1
ab)cd(ef
0
a(b[c{}d]e)f
1
a(b[c{)d]e}f
0

If only () need to be checked, keep only the first gsub(..)

HTH
--
Manuel Collado - http://mcollado.z15.es



reply via email to

[Prev in Thread] Current Thread [Next in Thread]