在 case 中使用括号对表达式进行分组

Using parentheses to group expressions in case

我想在 case 中用 () 对表达式进行分组,如下所示:

case a in
'*(a|b)*') printf '%s\n' 'something something';;
esac

虽然这没有取得任何成功。我也试过:

*(a|b)* *'('a|b')'* None 其中我取得了成功。

这将是 Bash 具体的:

您需要启用 extglob 并使用此特定语法

#!/usr/bin/env bash

shopt -s extglob

case "" in
*@(a|b)*) printf '%s\n' 'something something';;
esac

man bash:

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns:

  • ?(pattern-list)
    Matches zero or one occurrence of the given patterns
  • *(pattern-list)
    Matches zero or more occurrences of the given patterns
  • +(pattern-list)
    Matches one or more occurrences of the given patterns
  • @(pattern-list)
    Matches one of the given patterns
  • !(pattern-list)
    Matches anything except one of the given patterns

或者,您可以让 case 继续执行下一个模式的命令组,在命令组末尾使用特殊的 ;& 标记。

不是 POSIX,但由 bash[=25 处理=]zsh 还是:

#!/usr/bin/env ksh

case "" in
  *a*) ;& # Continue to next commands group
  *b*) printf '%s\n' 'something something';;
esac

现在,作为 that other guy pointed-out 在评论中。

POSIX方式:

#!/usr/bin/env sh

case "" in
  *a*|*b*) printf '%s\n' 'something something';;
esac

您可以转换为基本模式匹配,如下所示:

case 'a' in
*a*|*b*) printf '%s\n' 'something something';;
esac