Bash脚本中正则表达式怎么用
Bash脚本中正则表达式的用法
正则表达式是一个特殊的字符串,它能帮助你方便的检查一个字符串是否与某种模式匹配。Bash脚本中常用的正则表达式包括:
· ^:匹配字符串的开头
· $:匹配字符串的结尾
· .:匹配任意一个字符
· *:匹配任意个字符(包括0个)
· +:匹配至少一个字符
· ?:匹配0个或者1个字符
· {n}:匹配n个字符
· {n,}:匹配至少n个字符
· {n,m}:匹配n到m个字符
· [xyz]:匹配字符集合中的任意字符
· [^xyz]:匹配字符集合外的任意字符
· [a-z]:匹配从小写a到小写z的任意字符
· [A-Z]:匹配从大写A到大写Z的任意字符
· [0-9]:匹配数字集中的任意数字
· (ab):匹配子表达式ab
· |:匹配两个或者两个以上的表达式
· \:转义字符
下面我们通过一些例子来详细的介绍一下Bash脚本中正则表达式的用法。
例子1:匹配字符串的开头和结尾
#!/bin/bash
if [[ "my name is jack" =~ "^my.*jack$" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子2:匹配任意一个字符
#!/bin/bash
if [[ "my name is jack" =~ "a.e" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子3:匹配任意个字符
#!/bin/bash
if [[ "my name is jack" =~ "a.*e" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子4:匹配至少一个字符
#!/bin/bash
if [[ "my name is jack" =~ "a.+e" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子5:匹配0个或者1个字符
#!/bin/bash
if [[ "my name is jack" =~ "a.?e" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子6:匹配n个字符
#!/bin/bash
if [[ "my name is jack" =~ "a.{3}e" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子7:匹配至少n个字符
#!/bin/bash
if [[ "my name is jack" =~ "a.{3,}e" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子8:匹配n到m个字符
#!/bin/bash
if [[ "my name is jack" =~ "a.{2,4}e" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子9:匹配字符集合中的任意字符
#!/bin/bash
if [[ "my name is jack" =~ "[abc]" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子10:匹配字符集合外的任意字符
#!/bin/bash
if [[ "my name is jack" =~ "[^abc]" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子11:匹配从小写a到小写z的任意字符
#!/bin/bash
if [[ "my name is jack" =~ "[a-z]" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子12:匹配从大写A到大写Z的任意字符
#!/bin/bash
if [[ "my name is jack" =~ "[A-Z]" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
not matched
例子13:匹配数字集中的任意数字
#!/bin/bash
if [[ "my name is jack" =~ "[0-9]" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
not matched
例子14:匹配子表达式ab
#!/bin/bash
if [[ "my name is jack" =~ "(ab)" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
not matched
例子15:匹配两个或者两个以上的表达式
#!/bin/bash
if [[ "my name is jack" =~ "my|is" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
matched
例子16:转义字符
#!/bin/bash
if [[ "my name is jack" =~ "my\$name" ]]; then
echo "matched"
else
echo "not matched"
fi
输出结果为:
not matched
相关文章