I am trying to find multiple string patterns in a string in TCL. I cannot get the correct and optimized way to do that.
I have tried some code and it is not working
I have to find -h ,-he,-hel ,-help in the string -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"
}
how to use regexp here I am not sure , so need some inputs.
The expected output is
This is a case where using regexp is easier. (Asking if a string is a prefix of -help is a separate problem.) The trick here is to use ? and (…) (or rather (?:…) which is the non-capturing version) in the RE and you must use the -- option because the RE begins with a -:
if {[regexp -- {-h(?:e(?:lp?)?)?} $string]} {
puts "Found the string"
} else {
puts "Did not find the string"
}
If you want to know what string you actually found, add in a variable to pick up the overall match:
if {[regexp -- {-h(?:e(?:lp?)?)?} $string matched]} {
puts "Found the string '$matched'"
} else {
puts "Did not find the string"
}
If you instead want the indices where it matched, you need an extra option:
if {[regexp -indices -- {-h(?:e(?:lp?)?)?} $string match]} {
puts "Found the string at $match"
} else {
puts "Did not find the string"
}
If you were instead interested in whether the string was a prefix of -help, you instead should do:
if {[string equal -length [string length $string] $string "-help"]} {
puts "Found the string"
} else {
puts "Did not find the string"
}
Many uses of this sort of thing are actually doing command line parsing. In that case, the tcl::prefix command is very useful. For example, tcl::prefix match finds the entry in a list of options that a string is a unique prefix of and generates an error message when things are ambiguous or simply don't match; the result can be switched on easily:
set MY_OPTIONS {
-help
-someOtherOpt
}
switch [tcl::prefix match $MY_OPTIONS $string] {
-help {
puts "I have -help"
}
-someOtherOpt {
puts "I have -someOtherOpt"
}
}
Related
How can I get a single string variable with spaces in it in TCL to be interpreted as multiple arguments? I can't change the proc definition.
Here is an example of what I mean:
set my_options ""
if { "$some_condition" == 1 } {
append my_options " -optionA"
}
if { "$some_other_condition" == 1 } {
append my_options " -optionB"
}
set my_options [string trim $my_options]
not_my_proc ${my_options} ;# my_options gets interpreted as a single arg here and causes a problem:
# Flag '-optionA -optionB' is not supported by this command.
This is where you use the argument expansion syntax:
not_my_proc {*}$my_options
# ..........^^^
Although I'd recommend using a list instead of a string:
if for some reason the my_options string is not a well-formed list, you'll see an error thrown
if any of the options takes a space, a list is the proper data structure:
set my_options [list]
lappend my_options {-option1}
lappend my_options {-option2 "with a parameter"}
not_my_proc {*}$my_options
I'm trying to do a If not on a string match with Tcl. However, when I expect it not to match, it seems to be matching because when it shouldn't match it continues to "I don't want it to do this". Hope this makes sense. Inside the log.text file, it should contain, "This is a String."
set var1 "String"
set file [open "log.text" r]
while {[gets $file data] != -1} {
if {![string match *[string toupper $var1]* [string toupper $data]]} {
*I don't want it to do this
}
}
Your code appears to work fine:
$ cat log.text
This is a String
this line does not match
$ tclsh <<'END'
set var1 "String"
set file [open "log.text" r]
while {[gets $file data] != -1} {
if {![string match -nocase *$var1* $data]} {
puts "$data: does not match $var1"
}
}
END
outputs
this line does not match: does not match String
Ah, now you have clearly stated what you want: does the string exist in the file, yes or no. Here are some ways to accomplish that:
read the entire file, and string match against that.
set file [open log.text r]
set contents [read -nonewline $file]
close $file
set pattern_exists [string match -nocase *$var1* $contents]
if {$pattern_exists} {puts "$var1 found in file"}
read the file line-by-line until the pattern is found
set pattern_exists false
set file [open log.text r]
while {[gets $file line] != -1} {
if {[string match -nocase *$var1* $line]} {
set pattern_exists true
break
}
}
close $file
if {$pattern_exists} {puts "$var1 found in file"}
call out to grep to do the heavy lifting: grep exits with non-zero status when the pattern is not found, and exec thinks a non-zero exit status is an exception (see https://tcl.tk/man/tcl8.6/TclCmd/exec.htm#M27)
try {
exec grep -qi $var1 log.text
set pattern_exists true
} on error {e} {
set pattern_exists false
}
if {$pattern_exists} {puts "$var1 found in file"}
The code as you wrote it works… but I'm guessing it is a proxy for something else. If you are looking to see if an arbitrary string exists as a substring of a line, you are better off using string first instead of string match, since the latter has a few metacharacters (especially [ and ], which denote a set of characters) that can cause problems if you're not expecting them.
Try:
if {[string first [string toupper $var1] [string toupper $data]] >= 0} {
# The substring was there...
}
Alternatively, apply relevant backslash quoting when building your search pattern (possibly with string map) or use regexp, which has a useful find-a-literal mode:
if {[regexp -nocase ***=$var1 $data]} {
# The substring was there...
}
The ***= means “the rest of this pattern is a literal string to match” and we can pass -nocase as an option to allow us to not need to use string toupper.
According to the TCL man page for "string match" I should be able to do a character class. A simple example:
set rev revA
if { [string match "revA*" $rev } {
puts "revA"
} elseif {[string match "revB" $rev]} {
puts "revB"
} elseif {[string match "rev[CD]" $rev]} {
puts "revC or D"
} else {
puts "none"
}
Without the "rev[CD]" section it works fine but as shown above I get:
% tclsh tmp.tcl
missing close-bracket
What am I missing?
The real error is that you are actually missing a close bracket in the first if
if { [string match "revA*" $rev } {
# .............................^
Don't forget that [brackets] also signify Tcl's command substitution, and command substitution happens within double quotes. You need to either escape the open bracket or use different quotes:
} elseif {[string match "rev\[CD]" $rev]} {
} elseif {[string match {rev[CD]} $rev]} {
However, it's more efficient in this case, instead of cascading if-elseifs, to use switch
switch -glob -- $rev {
"revA*" {puts "revA"}
"revB" {puts "revB"}
{rev[CD]} {puts "revC or D"}
default {puts "none"}
}
Want to search within a file using tcl to find a match.
Here is what I have.
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
Not able to match "random string" with what's in the file. Appreciate any help.
If you want to use only string match, then use the glob pattern * here.
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
}
}
Output :
Found 'random string' in the line 'more random strings:1439413390'
Since we want to know whether the line contains the search string, we have added * at the beginning as well as in the end. It can match any number of sequence.
Reference : string match
In TCL, I have declared an array sstr with some patterns and I would like to match that patterns with the cryplist. If I found that match, I am displaying with array key and the matched list member. But the below program is not working. Hope I did some mistake in the declaration of regular expression.
#!/bin/tclsh
set cryplist [list "$:adzctg-cm20decadt/sr" "$:yyzpty-cm23febadt/sr" "dc*aed1740.0*gbp" "dc*ars1*usd" "dc*gbp10.00*/r" "d|t|lbb/den" "d|t|ordphx"]
array set sstr {
z "dc*[a-z]{3}*"
dl "d\$*[0-9]"
fd "\$:[a-z]{6}"
md "d|t|[a-z]{3}\/[a-z]{3}"
ms "d|t|[a-z]{6}"
}
foreach i $cryplist {
puts "------------- $i --------------"
foreach {n str} [array get sstr] {
puts "$n -> $str"
if { [regexp {$str} $i ] } {
puts "============= $n -> $i ================"
break
}
}
}
The problem is that you're using regexp {$str} $i, which makes the regular expression be the literal $str and not the contents of the str variable. Change to regexp -- $str $i and it should work; the -- says “no further options” (just for safety) and the unquoted $str reads from the variable for that argument (what you want).