use crate::{
evaluation::evaluator_value::EvaluatorValueRef, log_w, unwrap_or_return,
user::user_value::UserValueRef,
};
const TAG: &str = "CompareStrWithRegex";
pub(crate) fn compare_str_with_regex<'a>(
value: UserValueRef<'_>,
regex_value: impl Into<EvaluatorValueRef<'a>>,
) -> bool {
let regex_value = regex_value.into();
let value_str = unwrap_or_return!(value.string_value(), false);
let regex = match regex_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).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).into(), &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).into(), &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).into(), &right));
}
}