REGEX, Jsonata (Change node)

I use a change node to serve up responses to queries on a large array of unindexed notes:

$notes:=$globalContext("notes");
$searchFor:= req.query.searchFor;
$out:= $notes.**[label ~> $contains( $searchFor )] ;

It works well and is reasonably quick.
Unfortunately $contains() is case sensitive and not useful for "words only" searches so I would prefer to use a regex along the lines of:

$out:=  $notes.**[label ~> /($searchFor)/i] ;

but that, of course, just searches for "($searchFor)".
My question is: Can you construct, in a change node, a regex including a variable rather than a string literal?
(My guess is no; I've not found an example of such.)

The jsonata docs describe that $contains should be evaluated against a pattern.

Ie $contains(str, pattern)

You would have to use $eval to construct the regex.
$eval("/(" & $searchFor & ")/i")

You could also use $lowercase() in your original example

@E1cid Brilliant. Thanks for that! A case insensitive, words only search works fine:

    $sfCIWO:= "/^[^A-Za-z0-9_]*" & $searchFor & "[^A-Za-z0-9_]*$/i" ;
    $out:= [ $notes.**[label ~> ($eval($sfCIWO)) ] ];

I had to use longhand whitespace; use of valid regex metas (\w say) etc. elicits "Unsupported escape sequence: "w" . Obnoxious!

You would need to escape the \ so \w would be \\w

1 Like

@E1cid Mmm, yes, thank you. I did try that earlier today and the obnoxious error does disappear but it seems that \\w is passed to regex as \\w not \w - at least I think that's what happens as it didn't match correctly. I shall play again tomorrow.

You are incorrect \\w \\W \\setc are passed as \w \W \s. There must have been something else wrong with your regex.

@E1cid Good grief! The eval was correct. The regex was correct. The misleading errors were elsewhere entirely. Running fine now - many thanks for you help.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.