首页 > 解决方案 > 如何从期望测试 mySQL 响应中解析整数?

问题描述

有谁知道我如何在期望测试中从以下控制台输出中解析整数?

  +-----------------+
  | static_route_id |
  +-----------------+
  |             314 |
  +-----------------+

我想做的是

    proc testRouteId { identity_regex } {

          #sign into database (got it)

          #fetch routes with matching identity_regex (a column in the database)
          send { select static_route_id from static_routes where identity_regex="$identity_regex"; }
          send "\r"

          #parse the routeId out of the console output somehow
          expect {
            timeout { send_user "fetchStaticRouteId timed out\n"; return 0 }
            eof { send_user "fetchStaticRouteId failed\n"; return 0 }

          =========Stuck on the regex =========
            -re "REGEX?" { send_user "fetchStaticRouteId $expect_out(1, string)\n" }
          }
          return routeId; # (an int)
        }

标签: expect

解决方案


使用该expect命令匹配正则表达式模式,捕获由管道和空格包围的数字序列,并从expect_out数组中提取数字。

在这里,我使用 Tclformat命令(如 sprintf)使发送字符串更易于使用。您发送命令不会扩展变量,因为您使用大括号 - 请参阅https://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm规则编号 6。

send [format {select static_route_id from static_routes where identity_regex="%s";\r} $identity_regex]
expect -re {\|\s+(\d+)\s+\|.*}
return $expect_out(1,string)

推荐阅读