2

I am a newbie, and I'm having some trouble getting my tcl script working. I've searched around online, and can't seem to understand what I'm doing wrong. Here is what I wrote:

set list {f01-1 f01-2 f02-1 m01-1 m01-2 m02-1}
foreach item $list {
    if { [regexp {\w\d\d} $list match ] } {
        puts $match
    }
}

Here is the output I get:

f01
f01
f01
f01
f01
f01

However, this is what I would like to and expected to get:

f01
f01
f02
m01
m01
f02

Does anyone have any advice for getting what I expected?

Thank you ahead of time!

KaleidoEscape
  • 115
  • 1
  • 13
  • 2
    I'm less than a newbie in `tcl` but the foreach body doesn't refer to `item` at all. Is that intentional? :-) – azhrei Mar 18 '13 at 23:02
  • Your code snippet must not match what you're actually using, because a) `$string` isn't declared anywhere, and b) your regexp would actually spit out "f0", not "f01". – Lily Ballard Mar 18 '13 at 23:04
  • oops sorry! edited to what I actually have! (I'm also a newbie to posting, apparently... haha) – KaleidoEscape Mar 18 '13 at 23:05
  • It's a good idea to include some things in the list that aren't supposed to match when testing this sort of thing. Stops you from making silly mistakes. (Or at least it stops _me_ from making silly mistakes when I'm coding, and I'm guessing it'll work as a technique for you too!) – Donal Fellows Mar 19 '13 at 13:39
  • Thank you Donal Fellows, that's good advice... As I said, I am a newbie, still learning ^^; – KaleidoEscape Mar 20 '13 at 23:59

2 Answers2

4

Your code snippet doesn't seem to match your actual code, but I'm guessing that $string there is the same thing as $list, which means you're re-running the regexp on the original string repeatedly, instead of on each item. Furthermore your regexp was wrong. The following should work:

set list {f01-1 f01-2 f02-1 m01-1 m01-2 m02-1}
foreach item $list {
    if { [regexp {\w\d+} $item match ] } {
        puts $match
    }
}

The notable difference here, besides fixing your regexp, is it's now running it on $item instead of on $list.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • Thank you Kevin Ballard! That answers my question perfectly (and I feel like it's a silly mistake). I would upvote your answer if I had enough rep. =( – KaleidoEscape Mar 18 '13 at 23:08
  • @user2184303: You should still be able to accept answers though, right? Go ahead and click the checkbox next to my answer to mark it as accepted. This will have the side-effect of giving you +2 rep. – Lily Ballard Mar 18 '13 at 23:10
0

[regexp {\w\d\d} $list match ] will try to find the first occurrence of the specified RE in the given list.

Instead you should do this:

[regexp {\w\d\d} $item match ] which will check each item and prints if the RE is matched!

Mashhood
  • 391
  • 3
  • 10