#!/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
によって呼び出され、古き良き、bashの正規表現の一致のために少し単位スクリプトです非常に簡単に見えますが、失敗した実行している、この利回り:
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:]'
と
01を期待しますMatch of 'A6' against 'A[:digit:]+'
が成功する。
私は間違っていますか?
'[:桁は:]'広場の間で囲む必要があります。角かっこ。 => '[[:digit:]]' –
@CasimiretHippolyte OUCH!さて、これを答えにしてください... –
それ以外は '[:digt]'または '[id:tg]' ... –