用于检查字符串的Shell脚本正则表达式

时间:2015-04-09 17:31:34

标签: regex linux bash shell

我试图在shell脚本中编写一个简单的正则表达式,但我无法匹配任何东西。我不确定我的正则表达式是不正确还是我的shell代码不正确

#!/bin/sh
#
# This hook verifies that the commit message contains a reference to a tfs item

# Regex to validate a string contains "#" and 4 or 5 digits
regex="/#\d{4,5}/"
param=$1
echo "param = $param"
echo "regex = $regex"

if [[ $param =~ $regex ]]; then
  output="yes"
else
  output="no"
fi

echo "output = $output"

...

我正在使用$ ./myscript "#1234"$ ./myscript "asdf #1234 asdf"运行我的脚本,这些应该输出"是"

1 个答案:

答案 0 :(得分:2)

regex="/#\d{4,5}/"

BASH的正则表达式不正确。您可以使用:

regex="#[0-9]{4,5}"
  • BASH正则表达式中没有正则表达式分隔符
  • \d,不支持\w属性