Escape string for putting it into regex in TCL

隐身守侯 提交于 2019-12-24 00:34:33

问题


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{}}]

回答1:


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\$


来源:https://stackoverflow.com/questions/15042826/escape-string-for-putting-it-into-regex-in-tcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!