匹配 case 语句中的字母数字字符

Match alphanumeric characters in case statement

我需要检查我的脚本,</code> 是否是有效的主机名、指定端口的主机名 (host:port) 或其他内容。</p> <p>第一个案例工作正常,但第二个(<code>([a-z0-9.-]+))没有

case  in
   (*:*)
   foo
    ;;
   ([a-z0-9.-]+)
   bar
    ;;
   (*)
    asdf
    ;;
esac

如何在 case 语句中只匹配由 [a-z0-9.-] 组成的字符串?

加号在pattern matching notation中没有任何特殊含义。

在这种情况下,您需要采取相反的方法,在处理有效字符串之前处理无效字符串。例如:

case  in
*[!a-z0-9.-]*)
  # handle string that contains non-*alphanumeric* characters
  ;;
*)
  # handle string that consists of all *alphanumeric* characters
  ;;
esac

关于你的实际问题,我天真的尝试是:

# exclude non-ASCII characters from a-z and 0-9
LC_ALL=C

case  in
*:*:*)
  # handle string that contains multiple colons
  ;;
*:*[!0-9]*)
  # handle string that contains non-digit characters after the colon
  ;;
*[!a-z0-9.-]*:*)
  # handle string that consists of an invalid hostname and a valid port
  ;;
*:*)
  # handle string that consists of a valid hostname and port
  # perform further validation of hostname and port
  ;;
*[!a-z0-9.-]*)
  # handle string that forms an invalid hostname
  ;;
*)
  # handle string that forms a valid hostname
  # perform further validation of hostname
  ;;
esac