Regex bash正则表达式中的匹配组
在bash中,我有以下内容:Regex bash正则表达式中的匹配组,regex,bash,Regex,Bash,在bash中,我有以下内容: REGEX="(1.0.0|2.0.0)" declare -a arr=("A:1.0.0" "B:1.0.0" "C:2.0.0" "D:2.0.1") for i in "${arr[@]}" do echo "Found: $i" if [[ "$i"=~"${REGEX}" ]]; then echo "$i matches: ${REGEX}" else echo "$i DOES NOT matc
REGEX="(1.0.0|2.0.0)"
declare -a arr=("A:1.0.0" "B:1.0.0" "C:2.0.0" "D:2.0.1")
for i in "${arr[@]}"
do
echo "Found: $i"
if [[ "$i"=~"${REGEX}" ]]; then
echo "$i matches: ${REGEX}"
else
echo "$i DOES NOT match: ${REGEX}"
fi
done
我假设对于D:2.0.1
它将打印…不匹配…
,而是打印
Found: A:1.0.0
A:1.0.0 matches: (1.0.0|2.0.0)
Found: B:1.0.0
B:1.0.0 matches: (1.0.0|2.0.0)
Found: C:2.0.0
C:2.0.0 matches: (1.0.0|2.0.0)
Found: D:2.0.1
D:2.0.1 matches: (1.0.0|2.0.0)
那么我的正则表达式组模式有什么问题?指定这样的组模式在其他语言中也可以很好地工作,例如groovy。您首先在regex匹配表达式中遇到了一个输入错误
if [[ "$i"=~"${REGEX}" ]]; then
应该写得公正
if [[ $i =~ ${REGEX} ]]; then
if [[ $i =~ "${REGEX}" ]]; then
这意味着你永远不应该引用你的正则表达式。为了让它理解扩展正则表达式支持(ERE)中的|
运算符,您需要让它明白,它不是一个在双引号下处理的文本字符串
不推荐 但是,如果您仍然想引用您的正则表达式字符串,它将bash正则表达式的引用行为恢复到3.1版本,该版本支持引用正则表达式字符串。您只需要通过扩展shell选项启用它
shopt -s compat31
现在用引号运行它