如何在TCL中的字符串中找到','

时间:2014-11-14 23:26:24

标签: tcl

我是TCL的新手,只是想知道我们如何在字符串中搜索“,”并且想要前后的特定字符串。 示例:tampa,florida

它必须搜索,如果在那个字符串中,如果有,它应该返回坦帕和佛罗里达我们可以使用字符串替换但它不能在我的条件下工作,因为我需要映射,坦帕和佛罗里达到不同的变量集甚至不知道入站如何使用字符串范围。                                                                      

谢谢, 艾莉亚

3 个答案:

答案 0 :(得分:4)

除非有进一步的条件,否则你可以这样做:

split tampa,florida ,

该命令给出一个包含两个字符串“tampa”和“florida”的列表。

文档:split

答案 1 :(得分:3)

执行此操作的最短代码将使用正则表达式:

if {[regexp {(.+),(.+)} $string a b c]} {
   # $a is the complete match. But we don't care
   # about that so we ignore it

   puts $b; #tampa
   puts $c; #florida
}

正则表达式(.+),(.+)表示:

(
  .  any character
  +  one or more of the above
)    save it in a capture group
,    comma character
(
  .  any character
  +  one or more of the above
)    save it in a capture group

有关正则表达式的更多信息,请参阅tcl中正则表达式语法的文档:https://www.tcl.tk/man/tcl8.6/TclCmd/re_syntax.htm


但是,如果您不熟悉正则表达式并希望采用其他方法来执行此操作,则可以使用各种string命令。这是一种方法:

set comma_location [string first "," $string]
if {$comma_location > -1} {
    set a [string range $string 0 [expr {$comma_location -1}]
    set b [string range $string [expr {$comma_location +1}] end]
    puts $a; #tampa
    puts $b; #florida
}

答案 2 :(得分:0)

slebetman的最后一个答案。

proc before_after {value find {start 0}} {
    set index [string first $find $value $start]
    set left_side [string range $value $start [expr $index - 1]]
    set right_side [string range $value [expr $index + 1] end]
    return [list $left_side $right_side]
}

puts [before_after "tampa,fl" ","]

输出:

tampa fl