Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether string contains fragment in Tcl

Tags:

string

tcl

I have a set of words, e.g. {6-31G*, 6-311G*, 6-31++G*, 6-311++G**}. As you may see, the common fragment is "6-31". What I need to do in Tcl now is to check whether string under $variable contains this fragment. I know I could do it with regular expression like this:

if {[regexp {^6-31} $variable]} {
  puts "You provided Pople-style basis set"
}

but what other solution could I use (just out of curiosity)?

like image 865
user2300369 Avatar asked Dec 09 '16 18:12

user2300369


People also ask

How do you check if a string contains a substring in Tcl?

The string commandUse 'first' or 'last' to look for a substring. The return value is the index of the first character of the substring within the string. The 'string match' command uses the glob-style pattern matching like many UNIX shell commands do. Matches any number of any character.

What is lindex in Tcl?

DESCRIPTION. The lindex command accepts a parameter, list, which it treats as a Tcl list. It also accepts zero or more indices into the list. The indices may be presented either consecutively on the command line, or grouped in a Tcl list and presented as a single argument.

Is everything a string in Tcl?

In a Tcl script, everything is a string, and Tcl assigns no meaning to any string, making it a typeless language: Since a string has no particular value, it also has no particular type.


1 Answers

Just to check if a string contains a particular substring, I'd use string first

set substring "6-31"
if {[string first $substring $variable] != -1} {
    puts "\"$substring\" found in \"$variable\""
}

You can also use glob-matching with string match or switch

switch -glob -- $variable {
    *$substring* {puts "found"}
    default      {puts "not found"}
}
like image 92
glenn jackman Avatar answered Oct 18 '22 03:10

glenn jackman