RE匹配运算符不在此脚本中工作

时间:2016-04-16 14:29:45

标签: bash

奇怪的是,[[ 111-11-1111 =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]]只是在命令行上取得成功。

但是当我bash re.sh 111-11-1111

时,这个脚本不能产生相同的效果
#!/bin/bash
# re.sh

input=$1


if [[ "$input" =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]]
#                 ^ NOTE: Quoting not necessary, as of version 3.2 of Bash.
# NNN-NN-NNNN (where each N is a digit).
then
  echo "Social Security number."
  # Process SSN.
else
  echo "Not a Social Security number!"
  # Or, ask for corrected input.
fi

为什么?

1 个答案:

答案 0 :(得分:1)

正如其他人所提到的,如果您使用bash 3.2或更高版本,则应删除正则表达式上的引号。不过,这里的表达方式较短:

if [[ $input =~ ^[0-9]{3}-[0-9]{2}-[0-9]{4}$ ]]
相关问题