I use Expect
作为测试框架并编写一些辅助函数来简化匹配模式的键入expect
命令。
因此,我寻找将任何字符串转换为字符串的函数,其中所有特殊的正则表达式语法都被转义(例如*
, |
, +
, [
和其他字符),这样我就可以将任何字符串放入正则表达式中,而不必担心我会破坏正则表达式:
expect -re "^error: [escape $str](.*)\\."
refex "^error: [escape $str](.*)\\." "lookup string..."
For expect -ex
and expect -gl
编写转义函数非常容易。但对于expect -re
太难了,我是TCL新手……
PS我编写了这段代码,目前正在测试它们:
proc reEscape {str} {
return [string map {
"]" "\\]" "[" "\\[" "{" "\\{" "}" "\\}"
"$" "\\$" "^" "\\^"
"?" "\\?" "+" "\\+" "*" "\\*"
"(" "\\(" ")" "\\)" "|" "\\|" "\\" "\\\\"
} $str]
}
puts [reEscape {[]*+?\n{}}]
一种安全的策略是转义所有非单词字符:
proc reEscape {str} {
regsub -all {\W} $str {\\&}
}
The &
将被表达式中匹配的内容替换。
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\$
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)