gpt4 book ai didi

regex - 使用 '=~' 运算符的 Bash 正则表达式匹配意外失败

转载 作者:行者123 更新时间:2023-11-29 09:23:00 25 4
gpt4 key购买 nike

这是一个小单元脚本,用于由 =~ 调用的良好的旧 bash 正则表达式匹配

#!/bin/bash

# From "man bash"
# An additional binary operator, =~, is available, with the same
# precedence as == and !=. When it is used, the string to the right of
# the operator is considered an extended regular expression and matched
# accordingly (as in regex(3)). The return value is 0 if the string
# matches the pattern, and 1 otherwise. If the regular expression
# is syntactically incorrect, the conditional expression's return value
# is 2.

# The above should say regex(7) of course

match() {
local REGEX=$1
local VAL=$2
[[ $VAL =~ $REGEX ]]
RES=$?
case $RES in
0) echo "Match of '$VAL' against '$REGEX': MATCH" >&2 ;;
1) echo "Match of '$VAL' against '$REGEX': NOMATCH" >&2 ;;
2) echo "Error in regex expression '$REGEX'" >&2 ;;
*) echo "Unknown returnvalue $RES" >&2 ;;
esac
echo $RES
}

v() {
SHALL=$1
IS=$2
if [ "$SHALL" -eq "$IS" ]; then echo "OK"; else echo "NOT OK"; fi
}

unit_test() {
v 0 "$(match A A )"
v 0 "$(match A. AB )"
v 0 "$(match A[:digit:]? A )"
v 0 "$(match A[:digit:] A6 )"
v 0 "$(match \"A[:digit:]*\" A6 )" # enclosing in quotes needed otherwise fileglob happens
v 0 "$(match A[:digit:]+ A6 )"
v 0 "$(match A BA )"
v 1 "$(match ^A BA )"
v 0 "$(match ^A Ab )"
v 0 "$(match 'A$' BA )"
v 1 "$(match 'A$' Ab )"
}

unit_test

看起来很简单,但运行它会产生:

Match of 'A' against 'A': MATCH
OK
Match of 'AB' against 'A.': MATCH
OK
Match of 'A' against 'A[:digit:]?': MATCH
OK
Match of 'A6' against 'A[:digit:]': NOMATCH
NOT OK
Match of 'A6' against 'A[:digit:]*': MATCH
OK
Match of 'A6' against 'A[:digit:]+': NOMATCH
NOT OK
Match of 'BA' against 'A': MATCH
OK
Match of 'BA' against '^A': NOMATCH
OK
Match of 'Ab' against '^A': MATCH
OK
Match of 'BA' against 'A$': MATCH
OK
Match of 'Ab' against 'A$': NOMATCH
OK

人们期待

Match of 'A6' against 'A[:digit:]'

Match of 'A6' against 'A[:digit:]+'

成功。

我做错了什么?

最佳答案

请记住将字符类括在方括号 [] 中,以将它们匹配为字符列表,即 [[:digit:]]

string="A6"
[[ $string =~ A[[:digit:]] ]]
echo $?
0

Bracket-Expressions 上查看更多信息.

关于regex - 使用 '=~' 运算符的 Bash 正则表达式匹配意外失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41874468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com