空手道:与参数化正则表达式匹配

Karate: match with parametrized regex

我没有找到使用包含变量的正则表达式编写匹配项的正确方法:

* def getYear =
  """
  function() {
    var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
    var sdf = new SimpleDateFormat('yyyy');
    var date = new java.util.Date();
    return sdf.format(date);
  } 
  """
* def currentYear = getYear()
* def testmatch = { gencode: '#("000" + currentYear + "0000012345")' }
* match testmatch == { gencode: '#regex "[0-9]{3}" + currentYear + "[0-9]{10}"' }

有办法吗?

谢谢, 洛伦佐

首先,通常当你做这样的匹配时,正则表达式是不必要的,因为你还不如做一个精确匹配。

但无论如何这是解决方案,参考:https://github.com/intuit/karate#self-validation-expressions

* def isValidYear = function(x){ return new RegExp("[0-9]{3}" + currentYear + "[0-9]{10}").test(x) }
* assert isValidYear('00020190000012345')
* match testmatch == { gencode: '#? isValidYear(_)' }