Question : "regexp" in Tcl Scripts

I have a variavle "str" that contains ph#. I like to check
if it contains any char other than 0123...89. I wrote in Tcl script:

set str "6093994474"
if { [regexp { [0-9] } $str match] == 1 } {
puts "Ph# OK"
} else {
puts "BAD #"
}

It is not working! //Syntax ok but not giving correct o/p
Help please.Thanks.

Answer : "regexp" in Tcl Scripts


Ok. Tcl is a script language (tool command language) made
by Ousterhout of Berkley University using C language.


JUMP to **** ALTERNATE SCRIPT **** if you don't want to
read more explanations ...


The problem with the scripts above is the use of {}, []
and }{ or }else{.

You will get the message extra characters after close
brace if you not put a space between close brackets, for
ex.: } else { .

In Skundu's script the problem is that you will get always
a #BAD because the [] are used for command substitution in
tcl and the {} can be used like "" to construct strings
preventing substitutions even that characters with meaning
to tcl interpreter be used. For ex.: puts {$str} will
return a $str literal string and not the value
of variable.

In your script the regexp is in fact matching the literal
string "[0-9]" ! For tcl this is the same that write
{[0-9]}.

The "" don't prevent the command [] or $var substitution.
For ex. puts {[0-9]} the result will be [0-9], but
puts "[0-9]"
will result in an invalid command name because 0-9 doesn't
exist like a command. For ex. puts "[glob *]" will display
all file names in the current directory because glob is
a command for it and * it's argument. I would use the
following alternate script for the problem:


**** ALTERNATE SCRIPT ****

#!/usr/local/bin/tclsh
#--------------------------------------------------
#  Tested on tclsh 8.22 for windows
#  04-Mar-2001
#
# 1. Check the str var.
#
# 2. If it contains any char other than: 0123456789
#    Displays the error: BAD #
#    The chars ==>> any other <<== are not valid !!!!"
#
# 3. If not; displays:  Ph# OK"
#
# NOTE: str var remain unchanged.
#----------------------------------------------------

#-----------------------  Preset used variables
set str         "6093994474"
set str_aux     $str
set i           0


#------------ Extracts all chars not in [0..9] of str
#------------ and put then in the str_aux var
while {$i < 10} {
regsub -all "$i" $str_aux "" str_aux
incr i
}


#------- If str_aux is > 0 is because there is
#------- something other than 0 1 2 3 4 5 6 7 8 9
#------- in str var.
if {[string length $str_aux] > 0} {
puts "BAD #"
puts "The chars ==>> $str_aux <<== are not valid !!!!"
} else {
puts "Ph# OK"
}

Random Solutions  
 
programming4us programming4us