Lorenzo Nardi
Lorenzo Nardi

Reputation: 135

Karate: match with parametrized regex

I didn't find the right way to write a match with regexp cointaining a variable:

* 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}"' }

There is a way to do this?

Thanks, Lorenzo

Upvotes: 1

Views: 5735

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

First, normally when you are doing matches like this, regex is un-necessary, because you might as well do an exact match.

But anyway this is the solution, refer: 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(_)' }

Upvotes: 2

Related Questions