简体   繁体   English

tcl遍历列表中的项目时获得正则表达式匹配

[英]tcl getting a regexp match when iterating over items in a list

I am a newbie, and I'm having some trouble getting my tcl script working. 我是新手,我无法正常使用tcl脚本。 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! 提前谢谢你!

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. 您的代码段似乎与您的实际代码不匹配,但是我猜$string$list有相同的含义,这意味着您要在原始字符串上重复运行regexp,而不是在每个字符串上重复运行项目。 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 . 除了修复您的正则表达式外,这里的显着区别是它现在在$item而不是$list上运行它。

[regexp {\\w\\d\\d} $list match ] will try to find the first occurrence of the specified RE in the given list . [regexp {\\ w \\ d \\ d} $ list match]将尝试在给定列表中查找指定RE的第一个匹配项。

Instead you should do this: 相反,您应该这样做:

[regexp {\\w\\d\\d} $item match ] which will check each item and prints if the RE is matched! [regexp {\\ w \\ d \\ d} $ item match]将检查每个项目并打印RE是否匹配!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM