【问题标题】:Tcl: Removing the pound sign commented lineTcl:删除井号注释行
【发布时间】:2015-08-09 09:22:18
【问题描述】:

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

#!/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

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

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

【问题讨论】:

  • 你期待什么输出?

标签: tcl


【解决方案1】:

编辑后编辑回答:

#!/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 告诉返回与-all -inline 不匹配的元素


旧答案:

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

看看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 {\1}]

puts $out

对于正则表达式(完整详细信息here):

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

我们替换为\1,这是第一个捕获组(在这种情况下也是唯一一个)。

输出:

file1.bmp {

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

【讨论】:

  • @RobinHsu 更新了答案
  • 谢谢。这样可行。然而我稍微调整了一下:set out [lsearch -regexp -all -inline -not $lines {^\s*(#.*)?$}] 同时删除空行。
  • @RobinHsu 是的,虽然没有,我更新了答案。感谢更新
  • @robin 我已经回滚游览编辑因为 1)它不会摆脱空行和 2)编辑摘要没有理由放在答案中
猜你喜欢
  • 2018-07-28
  • 2012-10-15
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 2011-07-22
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多