tcl Matching a literal string with a regular expression


Example

Sometimes you need to match a literal (sub-)string with a regular expression despite that substring containing RE metacharacters. While yes, it's possible to write code to insert appropriate backslashes to make that work (using string map) it is easiest to just prefix the pattern with ***=, which makes the RE engine treat the rest of the string as just literal characters, disabling all further metacharacters.

set sampleText "This is some text with \[brackets\] in it."
set searchFor {[brackets]}

if {[ regexp ***=$searchFor $sampleText ]} {
    # This message will be printed
    puts "Found it!"
}

Note that this also means you can't use any of the anchors.