gav*_*koa 2 escaping tcl expect
我使用Expect
测试框架并编写一些辅助函数来简化expect
命令匹配模式的类型.
所以我寻找那些将任何字符串转换成字符串,其中所有特殊的正则表达式的语法逃脱功能(如*
,|
,+
,[
等字符),这样我就可以把任何字符串转换成正则表达式,而不必担心我打破正则表达式:
expect -re "^error: [escape $str](.*)\\."
refex "^error: [escape $str](.*)\\." "lookup string..."
Run Code Online (Sandbox Code Playgroud)
对于expect -ex
和expect -gl
这是很容易写逃生功能.但是expect -re
因为我是TCL的新手很难...
PS我写这段代码,目前正在测试它们:
proc reEscape {str} {
return [string map {
"]" "\\]" "[" "\\[" "{" "\\{" "}" "\\}"
"$" "\\$" "^" "\\^"
"?" "\\?" "+" "\\+" "*" "\\*"
"(" "\\(" ")" "\\)" "|" "\\|" "\\" "\\\\"
} $str]
}
puts [reEscape {[]*+?\n{}}]
Run Code Online (Sandbox Code Playgroud)
一个安全的策略是逃避所有非单词字符:
proc reEscape {str} {
regsub -all {\W} $str {\\&}
}
Run Code Online (Sandbox Code Playgroud)
在&
将由任何表达式被匹配被取代.
例
% 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\$
Run Code Online (Sandbox Code Playgroud)