Check Whether String Contains Fragment in 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)?

1 Answer

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"}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest