我是TCL的新手,只是想知道如何在字符串中搜索「,」,並希望前後的特定字符串。 例子:佛羅里達州坦帕如何在TCL中的字符串中找到','
它來搜索,如果在該字符串是否存在,它應該返回坦帕和佛羅里達州,我們可以使用字符串替換,而是因爲我需要地圖,坦帕它不會在我的條件下工作和佛羅里達到不同的變量集甚至不知道入站將如何使用字符串範圍。 。
謝謝, 的Arya
我是TCL的新手,只是想知道如何在字符串中搜索「,」,並希望前後的特定字符串。 例子:佛羅里達州坦帕如何在TCL中的字符串中找到','
它來搜索,如果在該字符串是否存在,它應該返回坦帕和佛羅里達州,我們可以使用字符串替換,而是因爲我需要地圖,坦帕它不會在我的條件下工作和佛羅里達到不同的變量集甚至不知道入站將如何使用字符串範圍。 。
謝謝, 的Arya
最短一段代碼執行此將使用正則表達式:
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
}
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