【问题标题】:How to find multiple sub string patterns in a string in TCL如何在 TCL 中的字符串中查找多个子字符串模式
【发布时间】:2019-09-14 19:14:56
【问题描述】:

我试图在 TCL 中的一个字符串中查找多个字符串模式。我无法找到正确且优化的方法。

我尝试了一些代码,但它不起作用

我必须在 -help 字符串中找到 -h ,-he,-hel ,-help

set args "-help"
set res1 [string first "-h" $args] 
set res2 [ string first -he $args] 
set res3 [string first -hel $args]
set res4 [string first "-help" $args"]

if { $res1 == -1 || $res2 || $res3 || $res4 } {
   puts "\n string not found"
} else {
  puts "\n string found" 
}

这里我不确定如何使用正则表达式,所以需要一些输入。

预期的输出是

【问题讨论】:

  • 欢迎,维安。您发布的 sn-p 无效,存在过多或不匹配的双引号。另外,你的问题我也不清楚。每个string first 都会找到您显示的模式,并将匹配的起始索引返回到干草堆字符串中(在您的示例中始终为0,因为每个模式都以索引0 开头)。那么,有什么问题呢?

标签: tcl


【解决方案1】:

这是使用regexp 更容易的情况。 (询问字符串是否是 -help 的前缀是一个单独的问题。)这里的技巧是在 RE 并且您必须使用 -- 选项,因为 RE 以 - 开头:

if {[regexp -- {-h(?:e(?:lp?)?)?} $string]} {
    puts "Found the string"
} else {
    puts "Did not find the string"
}

如果你想知道你实际找到了什么字符串,添加一个变量来获取整体匹配:

if {[regexp -- {-h(?:e(?:lp?)?)?} $string matched]} {
    puts "Found the string '$matched'"
} else {
    puts "Did not find the string"
}

如果您想要匹配的索引,则需要一个额外的选项:

if {[regexp -indices -- {-h(?:e(?:lp?)?)?} $string match]} {
    puts "Found the string at $match"
} else {
    puts "Did not find the string"
}

如果您对字符串是否为 -help 的前缀感兴趣,您应该这样做:

if {[string equal -length [string length $string] $string "-help"]} {
    puts "Found the string"
} else {
    puts "Did not find the string"
}

这种东西的许多用途实际上是在做命令行解析。在这种情况下,tcl::prefix 命令非常很有用。例如,tcl::prefix match 在选项列表中查找字符串是其唯一前缀的条目,并在内容不明确或根本不匹配时生成错误消息;结果可以很容易地switched:

set MY_OPTIONS {
    -help
    -someOtherOpt
}
switch [tcl::prefix match $MY_OPTIONS $string] {
    -help {
        puts "I have -help"
    }
    -someOtherOpt {
        puts "I have -someOtherOpt"
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 2018-08-27
    • 2020-09-15
    • 1970-01-01
    • 2019-10-01
    • 2014-11-10
    • 1970-01-01
    • 2011-07-13
    相关资源
    最近更新 更多