使用字符串匹配来搜索文件
Using string match to search a file
想要使用 tcl 在文件中搜索以找到匹配项。
这是我的。
set search "random string"
set file [open "file.txt" r]
while {![eof $file]} {
gets $file data
if {[ string match [string toupper $search] [string toupper $data] ] } {
//works
} else {
//doesnt work
}
}
File.txt
chicken.dinner:1439143130
random.strings:1439143130
more random strings:1439413390
random.strings.that.contain-special.characters:1439441566
无法将 "random string" 与文件中的内容相匹配。感谢任何帮助。
如果您只想使用 string match
,请在此处使用 glob 模式 *
。
set search "random string"
set file [open "file.txt" r]
while {[gets $file data] != -1} {
if {[string match *[string toupper $search]* [string toupper $data]] } {
puts "Found '$search' in the line '$data'"
} else {
# does not match case here
}
}
输出:
Found 'random string' in the line 'more random strings:1439413390'
因为我们想知道该行是否包含搜索字符串,所以我们在开头和结尾都添加了 *
。它可以匹配任意数量的序列。
参考: string match
想要使用 tcl 在文件中搜索以找到匹配项。
这是我的。
set search "random string"
set file [open "file.txt" r]
while {![eof $file]} {
gets $file data
if {[ string match [string toupper $search] [string toupper $data] ] } {
//works
} else {
//doesnt work
}
}
File.txt
chicken.dinner:1439143130
random.strings:1439143130
more random strings:1439413390
random.strings.that.contain-special.characters:1439441566
无法将 "random string" 与文件中的内容相匹配。感谢任何帮助。
如果您只想使用 string match
,请在此处使用 glob 模式 *
。
set search "random string"
set file [open "file.txt" r]
while {[gets $file data] != -1} {
if {[string match *[string toupper $search]* [string toupper $data]] } {
puts "Found '$search' in the line '$data'"
} else {
# does not match case here
}
}
输出:
Found 'random string' in the line 'more random strings:1439413390'
因为我们想知道该行是否包含搜索字符串,所以我们在开头和结尾都添加了 *
。它可以匹配任意数量的序列。
参考: string match