1

Below is my tcl script for checking if there is any 0-9 number find in the variable.

    set a "abc"

    if {[ regexp {[0-9]*} $a ]} {
       puts "Found number in $a"
    } else {
       puts "Doesn't find number in $a"
    }

But when I run it, it reports "Found number in abc".

0

3 Answers 3

2

That's because you are using a regular expression that means "match 0 or more numbers". The string abc matches 0 numbers, so you get a positive result. Just remove the * ("0 or more") and it should work as expected:

set a "a2bc"

if {[ regexp {[0-9]} $a ]} {
        puts "Found number in $a"
} else {
        puts "Doesn't find number in $a"
}
1
  • @Fisher If this (or another) answer solved your issue, please take a moment and accept it by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites.
    – terdon
    May 16, 2017 at 16:23
1

In a regular expression, * means "zero or more of the previously specified character or class". So you are looking for any string with zero or more numerical characters. Which matches everything.

0

You can use glob-style patterns to solve this as well without needing the power of regular expressions:

if {[string match {*[0-9]*} $a]} { ...

See string match documentation.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .