0
votes

In the file I have something like this:

name(0) = 123
name(1) = 456
name(2) = 789

I want to write match string to array.

  for { set i 0 } { $i < 3 } { incr i } {
     regexp {name\($i\) =\s+(.*)} $line full($i) name($i)
  }

I don't know why regexp don't recognizes $i counter. If I write:

     regexp {name\(0\) =\s+(.*)} $line full($i) name($i)

working but only for first counter.

1

1 Answers

1
votes

Braces in Tcl quote the string literally, so no variable substitution is done. If you want variable substitution, use double quotes. Since you are quoting a regular expression, the backslashes will need to be escaped.

Convert:

{name\($i\) =\s+(.*)}

To:

"name\\($i\\) =\\s+(.*)"

Or as DKF has suggested. This makes it easier to see the regexp without all the backslashes

set pattern [format {name\(%d\) =\s+(.*)} $i]
regexp $pattern $line full($i) name($i)

References: Tcl syntax, regex syntax, format