From 76ab78d34292d76d120ea083ffe5992670260feb Mon Sep 17 00:00:00 2001 From: Niko Raes Date: Thu, 5 Sep 2024 13:09:15 +0200 Subject: [PATCH] Add StartsWith and EndsWith to extended grammar --- JexlNet.ExtendedGrammar/ExtendedGrammar.cs | 42 +++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/JexlNet.ExtendedGrammar/ExtendedGrammar.cs b/JexlNet.ExtendedGrammar/ExtendedGrammar.cs index 8a66046..37dc3cc 100644 --- a/JexlNet.ExtendedGrammar/ExtendedGrammar.cs +++ b/JexlNet.ExtendedGrammar/ExtendedGrammar.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -80,6 +80,14 @@ public ExtendedGrammar() AddFunction("includes", Contains); AddFunction("$includes", Contains); AddTransform("includes", Contains); + // StartsWith + AddFunction("startsWith", StartsWith); + AddFunction("$startsWith", StartsWith); + AddTransform("startsWith", StartsWith); + // EndsWith + AddFunction("endsWith", EndsWith); + AddFunction("$endsWith", EndsWith); + AddTransform("endsWith", EndsWith); // Split AddFunction("split", Split); AddFunction("$split", Split); @@ -564,6 +572,38 @@ public static JsonNode Contains(JsonNode input, JsonNode pattern) return false; } + /// + /// Returns true if the string str starts with the character sequence chars. + /// + /// startsWith(str, chars)$startsWith(str, chars)str|startsWith(chars) + /// true if the string str starts with the character sequence chars + public static JsonNode StartsWith(JsonNode input, JsonNode chars) + { + if (input is JsonValue value && chars is JsonValue charsValue) + { + string str = value.ToString(); + string charsStr = charsValue.ToString(); + return str.StartsWith(charsStr); + } + return false; + } + + /// + /// Returns true if the string str ends with the character sequence chars. + /// + /// endsWith(str, chars)$endsWith(str, chars)str|endsWith(chars) + /// true if the string str ends with the character sequence chars + public static JsonNode EndsWith(JsonNode input, JsonNode chars) + { + if (input is JsonValue value && chars is JsonValue charsValue) + { + string str = value.ToString(); + string charsStr = charsValue.ToString(); + return str.EndsWith(charsStr); + } + return false; + } + /// /// Splits a string into an array of substrings based on a specified separator. ///