得之我幸 失之我命

when someone abandons you,it is him that gets loss because he lost someone who truly loves him but you just lost one who doesn’t love you.

字符串的模糊比较

在多数版本的 bash 中,增加了 [[ 命令,其中有一个 =~ 操作符,可以用来判断某个字符串是否包含特定模式

使用 =~ 操作符时,其右边的字符串被认为是一个扩展正则表达式,如果右边的整个字符串用引号括起来,那么表示匹配这个字符串自身的内容,不再解析成正则表达式

注意无论右边是否加引号,两遍都是包含关系,不是完整匹配,即,判断右边的模式是否为左边字符串的子字符串,而不是判断右边的模式是否完全等于左边字符串

以下是 =~ 判断字符串是否全是数字的正确写法和常见误区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# 正确
function check_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:只判断了传入的第一个参数是否包含一个数字,并不判断出所有字符是否都是数字
function check_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:试图用 * 匹配整个左边的字符串,从字面上看像是可以匹配到全是数字的情况,但实际上,它还是会匹配一个数字的情况,只要有一个数字就会认为匹配,甚至还会匹配没有数字的情况
function check_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:把右边的字符串用引号括起来
function check_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
function check_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"

be slow to promise and quick to perform.