Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Testing whether a string matches any pattern from a list



> On 15/11/2024 10:29 GMT Peter Stephenson <p.w.stephenson@xxxxxxxxxxxx> wrote:
> > On 15/11/2024 00:12 GMT Philippe Altherr <philippe.altherr@xxxxxxxxx>
> > wrote: I have an array that contains a list of patterns and a
> > string. I would like to check whether the string matches any of the
> > patterns in the array. For example if patterns=("foo*" "*bar"), then a
> > test for "foob", "obar", and "foobar" should return true and one for
> > "ooba" should return false.
> >
> > I hoped that I could use the following:
> >
> > if [[ -v patterns[(k)$string] ]]; then ... fi;
> >
> > Unfortunately, the pattern matching effect of the subscript flag
> > (https://zsh.sourceforge.io/Doc/Release/Parameters.html#Subscript-Flags) (k)
> > only works for associative arrays, not for regular arrays.
> 
> I think you might be hitting a slightly different problem, that the test
> is taking place in a special context that doesn't do the pattern lookup.
> This is rather obscure so probably not intentional.
> 
> At least, the following does work for me (and doesn't
> seem to be dependent on any options I have):
> 
> % string=B\*
> % print $signals[(k)$string]
> BUS
> 
> See if this works:
> 
> local lookup=${patterns[(k)$string]}
> if [[ -n $lookup ]]; then
>    # ...
> fi

Actually, it's only -v that's special --- so you can simply do

if [[ -n ${patterns[(k)$string]} ]]; then
  # ...
fi

pws




Messages sorted by: Reverse Date, Date, Thread, Author