在TCL中正则表达式

时间:2012-08-10 00:35:57

标签: regex tcl

我必须在TCL中使用regexp解析这种格式。 这是格式

              wl -i eth1 country

              Q1 (Q1/27) Q1

我正在尝试使用country作为关键字来解析格式'Q1(Q1 / 27)Q1'。 如果它与使用以下regexp命令的国家/地区位于同一行,我可以这样做。

   regexp {([^country]*)country(.*)} $line match test country_value

但我怎样才能解决上述问题?

1 个答案:

答案 0 :(得分:2)

首先,你正在使用的正则表达式首先没有做正确的事情,因为[^country]匹配 set 字符,其中包含除了字母之外的所有字符。 country {所以它只与h以后的eth1匹配,因为之后需要country

默认情况下,Tcl使用整个字符串进行匹配,而换行符只是普通字符。 (还有一个选项可以通过指定-line来使它们变得特别,但默认情况下它不会启用。)这意味着如果我使用整个字符串并通过regexp将其与正则表达式一起提供,工作(好吧,你可能想在某个时候string trim $country_value)。这意味着您的真正的问题是在呈现正确的字符串以匹配。

如果你一次展示一行(也许是从文件中读取),并且你想在一行中使用匹配来触发下一行的处理,你需要在正则表达式匹配之外进行一些处理:

set found_country 0
while {[gets $channel line] >= 0} {
    if {$found_country} {
        # Process the data...
        puts "post-country data is $line"
        # Reset the flag
        set found_country 0
    } elseif {[regexp {(.*) country$} $line -> leading_bits]} {
        # Process some leading data...
        puts "pre-country data is $leading_bits"
        # Set the flag to handle the next line specially
        set found_country 1
    }
}

如果您想完全跳过空白行,请在if {$line eq ""} continue之前加if {$found_country} ...