Regex in KornShell
I am trying to check whether a variable is exactly two numbers but I can not seem to figure it out.
How do you do check regular expressions (regex) in KornShell 开发者_开发知识库(ksh)?
I have tried:
if [[ $month =~ "[0-9]{2}" ]]
if [[ $month = _[0-9]{2}_ ]]
I have not been able to find any docs on it.
Any insight?
case $month in
[0-9][0-9]) echo "ok";;
*) echo "no";;
esac
should work.
If you need full regexp search, you can use egrep
like this:
if echo $month | egrep -q '^[0-9]{2}$'
then
echo "ok"
else
echo "no"
fi
Ksh has supported limited extended patterns since ksh88, using the
special '(' pattern ')'
syntax.
In ksh88, the 'special' character prefixes change the number of matches expected:
'*' for zero or more matches
'+' at least one match
'@' for exactly one match
'?' for zero or one matches
'!' for negation
In ksh93, this was expanded with
'{' min ',' max '}'
to express an exact range:
for w in 1423 12 "" abc 23423 9 33 3 333
do
[[ $w == {1,3}(\d) ]] && print $w has between 1 and three digits
[[ $w == {2}(\d) ]] && print $w has exactly two digits
done
And finally, you can have perl-like clutter with '~', which introduces a whole new class of extensions,including full regular expressions with:
'~(E)( regex )'
More examples can be found in Finnbarr P. Murphy's blog
Where I come from, this is more likely to validate numeric months:
if (( $month >= 1 && $month <= 12 ))
or
[[ $month =~ ^([1-9]|1[012])$ ]]
or to include a leading zero for single-digit months:
[[ $month =~ ^(0[1-9]|1[012])$ ]]
ksh does not use regular expressions; it uses a simpler but still quite useful language called "shell globbing patterns". The key ideas are
- Classes like
[0-9]
or[chly]
match any character in the class. - The
.
is not a special character; it matches only.
. - The
?
matches any single character. - The
*
matches any sequence of characters. - Unlike regular expressions, shell globbing patterns must match the entire word, so it works as if it were a regexp it would always start with
^
and end with$
.
Globbing patterns are not as powerful as regular expressions, but they are much easier to read, and they are very convenient for matching filenames and simple words. The case
construct is my favorite for matching but there are others.
As already noted by Alok you probably want
case $number in
[0-9][0-9]) success ;;
*) failure;;
esac
Although possibly you might prefer not to match a two-digit number with initial zero, so prefer [1-9][0-9]
.
you can try this as well
$ month=100
$ [[ $month == {1,2}([0-9]) ]] && echo "ok" || echo "no"
no
$ [[ $month == [0-9][0-9] ]] && echo "ok" || echo "no"
no
$ month=10
$ [[ $month == {1,2}([0-9]) ]] && echo "ok" || echo "no"
ok
$ [[ $month == [0-9][0-9] ]] && echo "ok" || echo "no"
ok
精彩评论