You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Karate框架:Schema验证中如何使用变量实现正则匹配

解决Karate中用变量生成正则校验Schema的问题

你的第一种写法行不通,因为Karate的#regex指令会把后面的字符串当作纯正则表达式解析,不会识别里面的#(myVar)变量引用——也就是说它会去匹配字面量#(myVar)开头的url,而不是你变量里的https://google.com。

你想的字符串拼接思路是对的,但不能直接写在JSON Schema里,得提前把完整的正则表达式拼接好存成变量,再在Schema里引用。具体实现如下:

Scenario: Schema with variable
   * def myVar = 'https://google.com'
   # 提前拼接好完整的正则表达式
   * def urlRegex = '^' + myVar + '.*'
   Given path 'path'
   When method Get
   And match response == 
   """
   {
      "id": "#uuid",
      "name": "#string",
      "url": "#regex #(urlRegex)"
   }
   """

这样urlRegex变量会被解析成^https://google.com.*,#regex就能正确校验url是否以myVar的内容开头了。

另外,如果你想更简洁,也可以直接在定义urlRegex时用Karate支持的JS风格模板字符串:

* def urlRegex = `^${myVar}.*`

效果和字符串拼接完全一致,看你习惯哪种写法即可。

内容的提问来源于stack exchange,提问作者Loïc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 02:38:14