regex - 如何在 bash 脚本中使用正则表达式?

标签 regex bash conditional-statements

我想使用正则表达式检查变量是否具有有效年份。阅读bash manual我知道我可以使用运算符 =~

查看下面的示例,我希望看到“不正常”,但我看到“正常”。我做错了什么?

i="test"
if [ $i=~"200[78]" ]
then
  echo "OK"
else
  echo "not OK"
fi

最佳答案

它在 3.1 和 3.2 之间发生了变化:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

因此在不带引号的情况下使用它:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

关于regex - 如何在 bash 脚本中使用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/304864/

相关文章:

linux - 使用 bash 仅打印文件中的某些行

java - 提交在/workspace 中生成的文件的容器更改(即使使用 makefile)不会持续到图像的新实例中

Javascript - 基于动态填充下拉菜单的转到 url

Java Regex 检查字符串是否包含 XML 标记

javascript - 1-6 位数字的正则表达式,后跟 .nn

regex - sed 尝试在搜索和替换中使用捕获组时前面的正则表达式无效

angularjs - 指令模板中 ng 类中的条件逻辑

javascript - JavaScript 中的电子邮件验证

linux - 定期列出文件的 Bash 脚本

java - 为什么我不能在 for 循环条件中使用数学(减法)?