Add regex test to expression language (fixes #162)

This commit is contained in:
elkowar 2021-05-09 14:52:46 +02:00
parent b1cb74d386
commit 29c741466e
No known key found for this signature in database
GPG key ID: E321AD71B1D1F27F
2 changed files with 7 additions and 0 deletions

View file

@ -17,6 +17,7 @@ pub enum BinOp {
GT, GT,
LT, LT,
Elvis, Elvis,
RegexMatch,
} }
impl std::fmt::Display for BinOp { impl std::fmt::Display for BinOp {
@ -34,6 +35,7 @@ impl std::fmt::Display for BinOp {
BinOp::GT => write!(f, ">"), BinOp::GT => write!(f, ">"),
BinOp::LT => write!(f, "<"), BinOp::LT => write!(f, "<"),
BinOp::Elvis => write!(f, "?:"), BinOp::Elvis => write!(f, "?:"),
BinOp::RegexMatch => write!(f, "=~"),
} }
} }
} }
@ -156,6 +158,10 @@ impl AttrValExpr {
BinOp::GT => PrimVal::from(a.as_f64()? > b.as_f64()?), BinOp::GT => PrimVal::from(a.as_f64()? > b.as_f64()?),
BinOp::LT => PrimVal::from(a.as_f64()? < b.as_f64()?), BinOp::LT => PrimVal::from(a.as_f64()? < b.as_f64()?),
BinOp::Elvis => PrimVal::from(if a.0.is_empty() { b } else { a }), BinOp::Elvis => PrimVal::from(if a.0.is_empty() { b } else { a }),
BinOp::RegexMatch => {
let regex = regex::Regex::new(&b.as_string()?)?;
PrimVal::from(regex.is_match(&a.as_string()?))
}
}) })
} }
AttrValExpr::UnaryOp(op, a) => { AttrValExpr::UnaryOp(op, a) => {

View file

@ -111,6 +111,7 @@ fn parse_term1(i: &str) -> IResult<&str, AttrValExpr, VerboseError<&str>> {
map(preceded(tag("!="), parse_term2), |x| (BinOp::NotEquals, x)), map(preceded(tag("!="), parse_term2), |x| (BinOp::NotEquals, x)),
map(preceded(tag(">"), parse_term2), |x| (BinOp::GT, x)), map(preceded(tag(">"), parse_term2), |x| (BinOp::GT, x)),
map(preceded(tag("<"), parse_term2), |x| (BinOp::LT, x)), map(preceded(tag("<"), parse_term2), |x| (BinOp::LT, x)),
map(preceded(tag("=~"), parse_term2), |x| (BinOp::RegexMatch, x)),
)))(i)?; )))(i)?;
let exprs = remainder.into_iter().fold(initial, |acc, (op, expr)| AttrValExpr::BinOp(box acc, op, box expr)); let exprs = remainder.into_iter().fold(initial, |acc, (op, expr)| AttrValExpr::BinOp(box acc, op, box expr));