use crate::{
evaluation::evaluator_value::MemoizedEvaluatorValue, log_w, unwrap_or_return, DynamicValue,
};
const TAG: &str = "CompareStrWithRegex";
pub(crate) fn compare_str_with_regex(
value: &DynamicValue,
regex_value: &MemoizedEvaluatorValue,
) -> bool {
let value_str = unwrap_or_return!(&value.string_value, false);
let regex = match ®ex_value.regex_value {
Some(regex) => regex,
None => {
log_w!(
TAG,
"No regex value found. 'str_matches' operators require a call to EvaluatorValue::compile_regex() on the target value."
);
return false;
}
};
regex.is_match(&value_str.value).unwrap_or(false)
}
#[cfg(test)]
mod tests {
use crate::evaluation::comparisons::compare_str_with_regex;
use crate::{dyn_value, test_only_make_eval_value};
#[test]
fn test_compare_regex_simple() {
let left = dyn_value!("apple banana pear");
let mut right = test_only_make_eval_value!("banana");
right.compile_regex();
assert!(compare_str_with_regex(&left, &right));
}
#[test]
fn test_compare_regex_complex() {
let left =
dyn_value!(r#"{ "name": "Statsig", "version": "4.8.1-beta.32", "license": "ISC" }"#);
let mut right = test_only_make_eval_value!(r#"version":\s*"4\.8\.\d+"#); right.compile_regex();
assert!(compare_str_with_regex(&left, &right));
}
#[test]
fn test_compare_regex_fancy_fallback() {
let left = dyn_value!("foobar");
let mut right = test_only_make_eval_value!(r#"(?<=foo)bar"#);
right.compile_regex();
assert!(compare_str_with_regex(&left, &right));
}
}