Skip to content
Myr

regex_helper.rs

This file

Path

src/regex_helper.rs

52 lines · 1.8 KiB · Rust

Last changed by

Add tests for regex_helpersharkdpbefore adoption9ef9bf7

History of this file

Take it

Move regex helpers to new modulesharkdpbefore adoption809fd8f

lines 1–35why, one step back
1use regex_syntax::hir::Hir;
2use regex_syntax::ParserBuilder;34/// Determine if a regex pattern contains a literal uppercase character.5pub fn pattern_has_uppercase_char(pattern: &str) -> bool {6 let mut parser = ParserBuilder::new().allow_invalid_utf8(true).build();78 parser9 .parse(pattern)10 .map(|hir| hir_has_uppercase_char(&hir))11 .unwrap_or(false)12}1314/// Determine if a regex expression contains a literal uppercase character.15fn hir_has_uppercase_char(hir: &Hir) -> bool {16 use regex_syntax::hir::*;1718 match *hir.kind() {19 HirKind::Literal(Literal::Unicode(c)) => c.is_uppercase(),20 HirKind::Literal(Literal::Byte(b)) => char::from(b).is_uppercase(),21 HirKind::Class(Class::Unicode(ref ranges)) => ranges22 .iter()23 .any(|r| r.start().is_uppercase() || r.end().is_uppercase()),24 HirKind::Class(Class::Bytes(ref ranges)) => ranges25 .iter()26 .any(|r| char::from(r.start()).is_uppercase() || char::from(r.end()).is_uppercase()),27 HirKind::Group(Group { ref hir, .. }) | HirKind::Repetition(Repetition { ref hir, .. }) => {28 hir_has_uppercase_char(hir)29 }30 HirKind::Concat(ref hirs) | HirKind::Alternation(ref hirs) => {31 hirs.iter().any(hir_has_uppercase_char)32 }33 _ => false,34 }35}

Add tests for regex_helpersharkdpbefore adoption9ef9bf7

lines 36–52why, one step back
36
37#[test]38fn pattern_has_uppercase_char_simple() {39 assert!(pattern_has_uppercase_char("A"));40 assert!(pattern_has_uppercase_char("foo.EXE"));4142 assert!(!pattern_has_uppercase_char("a"));43 assert!(!pattern_has_uppercase_char("foo.exe123"));44}4546#[test]47fn pattern_has_uppercase_char_advanced() {48 assert!(pattern_has_uppercase_char("foo.[a-zA-Z]"));4950 assert!(!pattern_has_uppercase_char(r"\Acargo"));51 assert!(!pattern_has_uppercase_char(r"carg\x6F"));52}