regex - 使用正则表达式通过 Bash 检查范围

标签 regex linux bash unix

我创建了一个辅助函数来确定生成密码的指定长度是否有效。如果条件为正则表达式来检查 8-64 的范围,我该如何翻译它?

# Check to see if password length is valid
# @param $1 length specified by the user
# @return True (0) if not valid, False (1) if we're okay
# Usage: if is_valid "$length"
is_valid() {
  local length="$1"

  if (( "$length" < 8 || "$length" > 64 )); then
    return 0
  else
    return 1
  fi  
}

最佳答案

您可以使用普通模式匹配来代替正则表达式:

function is_valid () {
    [[ $1 == @([8-9]|[1-5][0-9]|[6][0-4]) ]]
}

正则表达式类似:

function is_valid () {
    [[ $1 =~ ^([8-9]|[1-5][0-9]|[6][0-4])$ ]]
}

我认为它们中没有任何一个比简单的更具可读性

function is_valid () {
    (( 8 <= $1 && $1 <= 64 ))
}

请注意,不需要 ifreturn

关于regex - 使用正则表达式通过 Bash 检查范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17982901/

相关文章:

swift - 正则表达式:捕获组和空字段(SWIFT 5 | ICU 正则表达式引擎)

c++ - dlopen() 返回 0

php - Symfony 路由正则表达式 : How to write an optional character?

regex - 使用正则表达式以任意顺序排列多个单词

regex - 有人可以解释吗? : in regular expression

windows - 将 linux 应用程序移植到 windows 的建议

linux - echo 3 >/proc/sys/vm/drop_caches 在 Mac OSX 上

linux - 将变量传递给 Linux bash 命令参数

linux - 重新排序 block 字符串

bash - 从另一个文件中删除包含 ID 的每一行