Tcl:删除井号注释行

Tcl: Removing the pound sign commented line

为什么我不能删除井号注释行?

#!/usr/bin/tclsh

set lines [list file1.bmp {  # file2.bmp} file3.bmp ]

# Now we apply the substitution to get a subst-string that
# will perform the computational parts of the conversion.
set out [regsub -all -line {^\s*#.*$} $lines {}]

puts $out

输出:

file1.bmp {  # file2.bmp} file3.bmp

-更新-

预期输出:

file1.bmp {} file3.bmp

{}表示空字符串。

事实上,这是我的第一步。我的最终目标是消除所有注释行和所有空行。上面的问题只是把所有的注释行都改成了空行。例如,如果输入是:

set lines [list file1.bmp {  # file2.bmp} {} file3.bmp ]

我希望我的最终结果是

file1.bmp file3.bmp

注意:Whosebug 错误地将井号 (#) 前后的所有内容变暗,认为这些是注释。然而在TCL语法中,它不应该是注释。

@Tensibai: 我还想删除空行,因此我匹配“#”之前的任意数量的空格。 (因为在删除所有包含的“#”之后,它是一个空行)。事实上,在我的数据中,评论总是单独显示为整行。但是“#”符号可能不会出现在第一个字符 => 空格可以引导注释行。

编辑后回答:

#!/usr/bin/tclsh

set lines [list file1.bmp { # file2.bmp } file3.bmp #test ]
puts $lines
# Now we apply the substitution to get a subst-string that
# will perform the computational parts of the conversion.
set out [lsearch -regexp -all -inline -not $lines {^\s*(#.*)?$}]

puts $out

输出:

file1.bmp file3.bmp

您正在处理一个 listlist 的表示是一个简单的文本,因此您可以 regsub 它,但它是一行。 如果你想检查这个列表中的元素,你必须使用列表相关命令。

这里 lsearch 会做你想做的事,检查每个项目看它们是否匹配正则表达式,-not 告诉 return 与 [=19= 不匹配的元素]


旧答案:

原因:因为您的正则表达式匹配任何以 0 或无限数量的空格开头的英镑。因此它只会匹配注释行而不匹配行内注释。

看看 http://regex101.com 来测试正则表达式。

一个有效的正则表达式是:

#!/usr/bin/tclsh

set lines [list file1.bmp {  # file2.bmp} file3.bmp ]

# Now we apply the substitution to get a subst-string that
# will perform the computational parts of the conversion.
set out [regsub -all -line {^(.*?)#.*$} $lines {}]

puts $out

对于正则表达式(完整的细节here):

  • ^ 匹配行首
  • (.*?)# 在 # 之前匹配并捕获尽可能有限数量的字符(非贪婪运算符 ? 以限制匹配)
  • .*$ 匹配任意数量的字符直到行尾

我们用 </code> 替换第一个捕获组(也是本例中唯一的一个)。</p> <p>输出:</p> <pre><code>file1.bmp {

这也将删除整行注释,但如果井号前有空格或制表符,则可能会留下空格或制表符,因此会留下空行。