【问题标题】:Dynamically adding flags to a command为命令动态添加标志
【发布时间】:2014-01-02 09:15:15
【问题描述】:

是否可以在不使用eval 的情况下为命令动态添加标志?

例如,我希望对变量执行以下操作:

set isCaseSensitive 1
if {$isCaseSensitive == 1} {
    set res [regexp -nocase -- $regexp $str]
} else {
    set res [regexp -- $regexp $str]
}

# The following does NOT work

set regexp_flags ""
if {$isCaseSensitive == 1} {
    append regexp_flags " -nocase"
}
set res [regexp $regexp_flags -- $regexp $str]

使用 Tcl 8.5


编辑 #1,世界标准时间 12:41:
(回复评论者 Jerry)

我已经执行了代码:

set regexp_flags ""
if {$isCaseSensitive == 1} {
    append regexp_flags "-nocase"
}

set res [regexp -line -all -inline -indices $regexp_flags -- $regexp $str]

并收到以下错误(省略无关文本):

regexp match variables not allowed when using -inline
    while executing
"regexp -line -all -inline -indices $regexp_flags -- $regexp $str"

这是因为 Tcl 认为 $str 是第四个参数,在使用 -inline 标志时这是被禁止的。

regexp command documentation


编辑 #2,世界标准时间 14:01:

显然出于某种原因,我的主题字符串 ($str) 中的不可打印字符对该命令有一些负面影响。 (Tcl 不是二进制保护的吗?)
我在尝试regexp 之前尝试删除这些字符,现在它可以按预期工作了。

set regexp_flags ""
if {$isCaseSensitive == 1} {
    append regexp_flags "-nocase"
}

set str [regsub -all -- {[^[:print:]\t\n\r\f\v]} $str ""]
set res [regexp -line -all -inline -indices $regexp_flags -- $regexp $str]

【问题讨论】:

  • 为什么不简单地append regexp_flags "-nocase"?它适用于我的 Tcl8.5。 (插入空间使其不再起作用)
  • @Jerry:请看我的第一次编辑。
  • 变量指的是捕获的组。我没有任何问题...这是demo,它在 8.4 上运行良好。
  • @Jerry 我找到了问题的原因。请参阅我的第二次编辑。谢谢! :)
  • 我刚刚注意到您的编辑 :) 没问题!

标签: tcl


【解决方案1】:

在 8.5 和 8.6 中,最好的办法是:

set regexp_flags ""
if {$isCaseSensitive == 1} {
    lappend regexp_flags -nocase
}

set res [regexp -line -all -inline -indices {*}$regexp_flags -- $regexp $str]

在 8.4 中(以及之前,如果你是真的老派!)你需要这个构造来代替(你肯定需要第二个[list …],因为RE 和字符串不太可能是简洁的裸词):

set regexp_flags ""
if {$isCaseSensitive == 1} {
    lappend regexp_flags -nocase
}

set res [eval [list regexp -line -all -inline -indices] $regexp_flags [list -- $regexp $str]]

虽然这样写可能更好:

set regexp_cmd [list regexp -line -all -inline -indices]
if {$isCaseSensitive == 1} {
    lappend regexp_cmd -nocase
}

set res [eval $regexp_cmd [list -- $regexp $str]]

您不想使用 8.5 吗?或者将(?i) 放在 RE 的前面(这也使它不区分大小写)?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 2010-11-10
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多