ilansh
ilansh

Reputation: 113

tcl regexp from variable and special characters

I am a bit confused my input string is " foo/1" my motivation is to set foo as a variable and regexp it :

set line " foo/1"
set a foo
regexp "\s$a" $line does not work

also I noticed that only if I use curly and giving the exact string braces it works

regexp {\sfoo} $line works
regexp "\sfoo" $line doesnt work

can somebody explain why? thanks

Upvotes: 0

Views: 4282

Answers (1)

Googie
Googie

Reputation: 6017

Quick answer:

"\\s" == {\s}

Long answer:

In Tcl, if you type a string using "" for enclosing it, everything inside will be evaluated first and then used as a string. This means that \s is evaluated (interpreted) as an escape character, instead of two characters.

If you want to type \ character inside "" string you have to escape it as well: \\. In your case you would have to type "\\sfoo".

In case of {} enclosed strings, they are always quoted, no need for repeated backslash.

Using "" is good if you want to use variables or inline commands in the string, for example:

puts "The value $var and the command result: [someCommand $arg]"

The above will evaluate $var and [someCommand $arg] and put them into the string.

If you'd have used braces, for example:

puts {The value $var and the command result: [someCommand $arg]}

The string will not be evaluated. It will contain all the $ and [ characters, just like you typed them.

Upvotes: 5

Related Questions