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

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



On Fri, Nov 15, 2024 at 1:13 AM 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.

You can join the elements of the array with "|" as the separator, and
then match against it:

    [[ $string == (${~${(j:|:)patterns}}) ]]

You could also restructure your code to have a single pattern to begin with:

    pattern='(foo*|*bar)'
    [[ $string == $~pattern ]]

Roman




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