Using variable reference in JavaRegex conditions

I am using a JavaRegex condition to test if a string variable matches/contains another variable.

For example:

var1 = "DEF"

var2 = "DEFGHIJ"

So the condition I am using is

<Condtion>var2 JavaRegex "^.*{var1}.*$"</Condition>

But apigee runtime is failing to replace var1 and resulting in exception being thrown.

Could someone please clarify this if apigee support variable replacements in regex? or I am doing something wrong here?

Thanks for help!

3 5 548
5 REPLIES 5

I don't believe you can use {} braces for variable substitution in the reg exp, as they signify a quantifier (no. of times the preceeding char is allowed in the input).

hi, Are there any solutions for this problem?

The JavaRegex operator takes a fixed string for the RHS. You cannot reference a variable there.

There is a workaround.  Use a preceding JS policy to dynamically construct and evaluate the regexp, then set a context variable with the result (match or no match).  Then just use a boolean check in your succeeding Condition, checking the result of that context variable. 

  <Step>
    <Name>JS-Check-Regexp</Name>
  </Step>
  <Step>
    <Name>whatever</Name>
    <Condition>my-custom-regexp-matched is true</Condition>
  </Step>
    ...

If you are applying the condition to a Flow, then you need to perform the JS check in the Preflow. 

Will that solve your problem? 

The JS code for evaluating a dynamic regexp looks like this: 

<Javascript name='JS-Check-Regexp'>
  <Source>
    const v1 = context.getVariable('var-to-embed');
    const re = new RegExp('^.*' + v1 + '.*$');
    const v2 = context.getVariable('var-to-check');
    const found = v2.match(re);
    context.setVariable('my-custom-regexp-matched', found?"true":"false");
  </Source>
</Javascript>

Thanks for the workaround, I'd say I can do that

Thanks @Hansel Miranda,

I want to use content of var1 in JavaRegex. How can I achieve that or is at all possible?

Like we can do a match for dynamic URL variables in MatchesPath in conditions.

Is there a similar approach for using variables in JavaRegex in a condition.