# 正确 functioncheck_digits() { local count=${#1}# 获取所传入第一个参数的字符串长度 if [[ "$1" =~ [0-9]{$count} ]] # [0-9]{n} 表示匹配 n 个连续的数字 then echo"All digits." else echo"Not all digits." fi }
$ check_digits 12345 All digits. $ check_digits abcd Not all digits. $ check_digits a2c Not all digits. $ check_digits 1b3 Not all digits.
# 误区 1:只判断了传入的第一个参数是否包含一个数字,并不判断出所有字符是否都是数字 functioncheck_digits() { if [[ "$1" =~ [0-9] ]] # [0-9] 表示匹配 0 到 9 之间的任意一个数字,但是只匹配一个数字 then echo"All digits." else echo"Not all digits." fi }
$ check_digits 12345 All digits. $ check_digits abcd Not all digits. $ check_digits 1b3d All digits. $ check_digits a2 All digits.
# 误区 2:试图用 * 匹配整个左边的字符串,从字面上看像是可以匹配到全是数字的情况,但实际上,它还是会匹配一个数字的情况,只要有一个数字就会认为匹配,甚至还会匹配没有数字的情况 functioncheck_digits() { if [[ "$1" =~ [0-9]* ]] # [0-9]* 表示匹配零个或多个连续的数字 then echo"All digits." else echo"Not all digits." fi }
$ check_digits 12345 All digits. $ check_digits abcd All digits. $ check_digits 1b3d All digits. $ check_digits a2 All digits.
# 误区 3:把右边的字符串用引号括起来 functioncheck_digits() { local count=${#1} if [[ "$1" =~ "[0-9]{$count}" ]] then echo"All digits." else echo"Not all digits." fi }
$ check_digits 12345 Not all digits. $ check_digits abcd Not all digits. $ check_digits 1b3d Not all digits. $ check_digits a2 Not all digits. $ check_digits [0-9]{8} All digits.
以下是 =~ 判断某个字符串是否为另一个字符串的子字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
functioncheck_substr() { if [[ "$1" =~ "$2" ]] # =~ 右边的 "$2" 加了双引号,不再当成正则表达式处理,只会比较字符串自身的内容 then echo [$1] contains [$2] else echo [$1] does not contain [$2] fi }
# 测试的时候,如果传入的字符串参数包含空格,要用双引号括起来 $ check_substr "This is a test string""test string" "This is a test string" contains "test string" $ check_substr "This is a test string""is a test" "This is a test string" contains "is a test" $ check_substr "This is a test string""isa test" "This is a test string" does not contain "isa test" $ check_substr "This is a test string""new string" "This is a test string" does not contain "new string"