2

I use Expect as testing framework and write some helper functions to simplify typing of matching patterns for expect command.

So I look for function that transform any string into string in which all special regex syntax escaped (like *, |, +, [ and other chars) so I would be able put any string into regex without worrying that I break regex:

expect -re "^error: [escape $str](.*)\\."
refex "^error: [escape $str](.*)\\."  "lookup string..."

For expect -ex and expect -gl it is pretty easy to write escape function. But for expect -re it is hard as I am newbie to TCL...

PS I write this code and currently test them:

proc reEscape {str} {
    return [string map {
        "]" "\\]" "[" "\\[" "{" "\\{" "}" "\\}"
        "$" "\\$" "^" "\\^"
        "?" "\\?" "+" "\\+" "*" "\\*"
        "(" "\\(" ")" "\\)" "|" "\\|" "\\" "\\\\"
    } $str]
}

puts [reEscape {[]*+?\n{}}]
gavenkoa
  • 45,285
  • 19
  • 251
  • 303

1 Answers1

7

One safe strategy is to escape all non-word characters:

proc reEscape {str} {
    regsub -all {\W} $str {\\&}
}

The & will be substituted by whatever was matched in the expression.

Example

% set str {^this is (a string)+? with REGEX* |metacharacters$}
^this is (a string)+? with REGEX* |metacharacters$

% set escaped [reEscape $str]
\^this\ is\ \(a\ string\)\+\?\ with\ REGEX\*\ \|metacharacters\$
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks! I read about this in tcl wiki but don't understand this technique. +1 – gavenkoa Feb 23 '13 at 18:40
  • I can't found original link but this helpful http://wiki.tcl.tk/989 (Regular Expression Examples). – gavenkoa Feb 23 '13 at 18:43
  • 1
    @gavenkoa What don't you understand about it? We'd be happy to help you understand. (Might be better done as its own question though, so that it is more searchable for other people. Asking multiple questions — as long as they're different — is absolutely OK here on Stack Overflow.) – Donal Fellows Feb 24 '13 at 13:20
  • @DonalFellows After some reading I become understand TCL regex syntax as whole, so there are no need for question... Thanks! – gavenkoa Feb 24 '13 at 14:58