2013-06-23 18 views
0

我試圖從符合以下格式文件中提取字符串:。TCL預計使用正則表達式提取字符串

AP [前四位] [第2個半字節] [3蠶食]

例如:AP30f7.0df6.e51c

下面的代碼捕獲與上面的字符串共享同一行的所有數據。我能做些什麼來阻止捕獲與上述字符串在同一行上發現的任何不需要的數據?

while { [gets $fchan inline] >= 0} { 
    switch -regexp -- $inline { 
     AP([a-f0-9]{4}\.[a-f0-9]{4}\.[a-f0-9]{4}) { 
      append default_name $inline\n 
     } 
    } 
} 

UPDATE:

發現周圍的工作。由於每條符合我指定條件的行都以所需的字符串開始,因此我將使用字符串範圍命令僅提取前16個字符。

while { [gets $fchan inline] >= 0} { 
    switch -regexp -- $inline { 
     AP([a-f0-9]{4}\.[a-f0-9]{4}\.[a-f0-9]{4}) { 
      set inline_mod [string range $inline 0 15] 
      append default_name $inline_mod\n 
     } 
    } 
} 

回答

1

switch命令有一些有用的選項,當你想在匹配RE的同時進行提取。尤其應該使用the -matchvar option

while { [gets $fchan inline] >= 0} { 
    switch -regexp -matchvar matched -- $inline { 
     AP([a-f0-9]{4}\.[a-f0-9]{4}\.[a-f0-9]{4}) { 
      # Extract the first and second elements 
      lassign $matched inline_mod triple 
      # With your sample of AP30f7.0df6.e51c 
      # $inline_mod is "AP30f7.0df6.e51c" 
      # $triple is "30f7.0df6.e51c" 
      append default_name $inline_mod\n 
     } 
    } 
} 

該手冊頁上還有一些例子。

+0

不錯,有效。順便提一下,-matchvar需要TCL 8.5。 – user1933231