Skip to content

Inconsistent Behavior When Using Regex Variables in JSONata 2.0.6 #749

@sartian

Description

@sartian

Problem

Shared regex variables from higher scopes used with $replace function produce different results on repeated use, violating immutability. Works correctly in 1.8.7/2.0.1, broken in 2.0.6.

Reproduction

( 
  /* input and expected output values */
  $input := "a,b,c";

  /* regex variable mutations within subcontexts */ 
  $pattern := /[,-]/;

  $calledOnce := [
    $input ~> $replace($pattern, "|")
  ];
  
  $calledTwice := [
    $replace($input, $pattern, "|"), $replace($input, $pattern, "|")
  ];

  $calledTwiceTwice := [
    $replace($input, $pattern, "|"), $replace($input, $pattern, "|")
  ];

  $calledThrice := [
    $replace($input, $pattern, "|"), $replace($input, $pattern, "|"), $replace($input, $pattern, "|")
  ];

  /* some test runs with multiple calls */
  {
    "1x": $calledOnce,
    "2x": $calledTwice,
    "3x": $calledThrice
  }
)

Expected Output (works in 1.8.7/2.0.1):

{
  "1x": [
    "a|b|c"
  ],
  "2x": [
    "a|b|c",
    "a|b|c"
  ],
  "3x": [
    "a|b|c",
    "a|b|c",
    "a|b|c"
  ]
}

Actual Output (fails in 2.0.6):

{
  "1x": [
    "a|b|c"
  ],
  "2x": [
    "a|b|,b,|b|c",
    "a|b,c"
  ],
  "3x": [
    "a|b|,|,b,|b|c",
    "a|b,c",
    "a|,|b,c"
  ]
}

Workarounds

  • Use inline regex: $replace(/[,;]/, "|")
  • Create fresh instances: $fresh := function() { /[,;]/ }

Impact

Breaks immutability and consistency guarantees - same input gives different output. Silent failure makes it problematic at best for production use.

Root Cause

Regex internal state isn't reset between uses? May be related to Issue #177 regex architecture.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions