### Version Parsing Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Example of parsing version strings. ```rust let version_pattern = Pattern::new(r"(\d+)\.(\d+)\.(\d+)").unwrap(); if let Some(caps) = version_pattern.captures("v1.2.3") { let major = caps.get(1); // Some("1") let minor = caps.get(2); // Some("2") let patch = caps.get(3); // Some("3") } ``` -------------------------------- ### IP Address Matching Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Example of matching IP addresses. ```rust let ip_pattern = Pattern::new(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}").unwrap(); assert!(ip_pattern.is_match("Server: 192.168.1.1")); ``` -------------------------------- ### Verify Installation Source: https://github.com/ksd-co/rexile/wiki/Installation A simple Rust code example to verify that ReXile is installed and working correctly. ```rust use rexile::Pattern; fn main() { let pattern = Pattern::new(r"\d+").unwrap(); assert!(pattern.is_match("123")); println!("ReXile is working!"); } ``` -------------------------------- ### Quick Start - Basic Usage Source: https://github.com/ksd-co/rexile/blob/main/examples/README.md Demonstrates basic ReXile usage including pattern creation, matching, capture groups, and finding positions. ```rust use rexile::{ReXile, Pattern}; // Basic matching let pattern = ReXile::new(r"\w+@\w+").unwrap(); assert!(pattern.is_match("user@domain")); // Capture groups let pattern = Pattern::new(r"(\w+)@(\w+)").unwrap(); if let Some(caps) = pattern.captures("admin@example") { println!("User: {:?}", caps.get(1)); // Some("admin") println!("Domain: {:?}", caps.get(2)); // Some("example") } // Find positions if let Some((start, end)) = pattern.find("Contact: admin@example") { println!("Found at: {}-{}", start, end); } ``` -------------------------------- ### Log Level Extraction Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Example of extracting log levels from text. ```rust let log_pattern = Pattern::new(r"..\[(\w+)\]").unwrap(); if let Some(caps) = log_pattern.captures("[ERROR] Connection failed") { println!("Level: {:?}", caps.get(1)); // Some("ERROR") } ``` -------------------------------- ### Run Examples Source: https://github.com/ksd-co/rexile/wiki/Contributing Command to run a specific example from the project. ```bash cargo run --example comprehensive ``` -------------------------------- ### Email Validation Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Example of using ReXile for email validation. ```rust let email_pattern = Pattern::new(r"(\w+)@(\w+\.\w+)").unwrap(); assert!(email_pattern.is_match("user@example.com")); ``` -------------------------------- ### Tips - Pre-compiling Patterns Source: https://github.com/ksd-co/rexile/blob/main/examples/README.md Example showing how to pre-compile a pattern for reuse to improve performance. ```rust let pattern = ReXile::new(r"\w+@\w+").unwrap(); // Compile once for line in lines { pattern.is_match(line); // Reuse many times } ``` -------------------------------- ### Example Execution Source: https://github.com/ksd-co/rexile/blob/main/AGENTS.md Commands to run examples, as used by CI. ```bash cargo run --release --example comprehensive all cargo run --release --example perf_compare ``` -------------------------------- ### Rexile Quick Start Examples Source: https://github.com/ksd-co/rexile/blob/main/README.md A comprehensive set of examples demonstrating various features of the Rexile crate, including literal matching, multi-pattern matching, wildcards, quantifiers, DOTALL mode, non-capturing groups, digit matching, identifier matching, quoted strings, word boundaries, range quantifiers, case-insensitive matching, lookarounds, backreferences, text replacement, and splitting. ```rust use rexile::Pattern; // Literal matching with SIMD acceleration let pattern = Pattern::new("hello").unwrap(); assert!(pattern.is_match("hello world")); assert_eq!(pattern.find("say hello"), Some((4, 9))); // Multi-pattern matching (aho-corasick fast path) let multi = Pattern::new("foo|bar|baz").unwrap(); assert!(multi.is_match("the bar is open")); // Dot wildcard matching (with backtracking) let dot = Pattern::new("a.c").unwrap(); assert!(dot.is_match("abc")); // . matches 'b' assert!(dot.is_match("a_c")); // . matches '_' // Greedy quantifiers with dot let greedy = Pattern::new("a.*c").unwrap(); assert!(greedy.is_match("abc")); // .* matches 'b' assert!(greedy.is_match("a12345c")); // .* matches '12345' let plus = Pattern::new("a.+c").unwrap(); assert!(plus.is_match("abc")); // .+ matches 'b' (requires at least one char) assert!(!plus.is_match("ac")); // .+ needs at least 1 character // Non-greedy quantifiers (NEW in v0.2.1) let lazy = Pattern::new(r"start{.*?}").unwrap(); assert_eq!(lazy.find("start{abc}end{xyz}"), Some((0, 10))); // Matches "start{abc}", not greedy // DOTALL mode - dot matches newlines (NEW in v0.2.1) let dotall = Pattern::new(r"(?s)rule\s+.*?}}").unwrap(); let multiline = "rule test {\n content\n}"; assert!(dotall.is_match(multiline)); // (?s) makes .* match across newlines // Non-capturing groups with alternation (NEW in v0.2.1) let group = Pattern::new(r#"(?:\"test\"|foo)"#).unwrap(); assert!(group.is_match("\"test\"")); // Matches quoted "test" assert!(group.is_match("foo")); // Or matches foo // Digit matching (DigitRun fast path - 1.4-1.9x faster than regex!) let digits = Pattern::new("\\d+").unwrap(); let matches = digits.find_all("Order #12345 costs $67.89"); // Returns: [(7, 12), (20, 22), (23, 25)] // Identifier matching (IdentifierRun fast path) let ident = Pattern::new("[a-zA-Z_]\\w*").unwrap(); assert!(ident.is_match("variable_name_123")); // Quoted strings (QuotedString fast path - 1.4-1.9x faster!) let quoted = Pattern::new("\"[^\"]+\"").unwrap(); assert!(quoted.is_match("say \"hello world\"")); // Word boundaries let word = Pattern::new("\\btest\\b").unwrap(); assert!(word.is_match("this is a test")); assert!(!word.is_match("testing")); // Range quantifiers (NEW in v0.4.7) let ip = Pattern::new(r"\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").unwrap(); assert!(ip.is_match("192.168.1.1")); // Matches IP addresses let year = Pattern::new(r"\\b\\d{4}\\b").unwrap(); assert_eq!(year.find("Year: 2024!"), Some((6, 10))); // Matches exactly 4 digits // Case-insensitive matching (NEW in v0.4.7) let method = Pattern::new(r"(?i)(GET|POST)").unwrap(); assert!(method.is_match("GET /api")); // Matches GET assert!(method.is_match("get /api")); // Also matches lowercase assert!(method.is_match("Post /data")); // Also matches Post // Lookahead - match prefix only if followed by pattern (NEW in v0.4.9) let lookahead = Pattern::new(r"foo(?=bar)").unwrap(); assert!(lookahead.is_match("foobar")); // Matches 'foo' followed by 'bar' assert!(!lookahead.is_match("foobaz")); // Doesn't match - not followed by 'bar' // Negative lookahead (NEW in v0.4.9) let neg_lookahead = Pattern::new(r"foo(?!bar)").unwrap(); assert!(neg_lookahead.is_match("foobaz")); // Matches 'foo' NOT followed by 'bar' assert!(!neg_lookahead.is_match("foobar"));// Doesn't match - followed by 'bar' // Lookbehind - match suffix only if preceded by pattern (NEW in v0.4.9) let lookbehind = Pattern::new(r"(?<=foo)bar").unwrap(); assert!(lookbehind.is_match("foobar")); // Matches 'bar' preceded by 'foo' assert!(!lookbehind.is_match("bazbar")); // Doesn't match - not preceded by 'foo' // Backreferences - match repeated patterns (NEW in v0.4.8) let backref = Pattern::new(r"(\w+)\s+\1").unwrap(); assert!(backref.is_match("hello hello")); // Matches repeated word assert!(!backref.is_match("hello world"));// Doesn't match - different words // Text replacement (NEW in v0.5.0) 🎉 let pattern = Pattern::new(r"\\d+").unwrap(); assert_eq!(pattern.replace("Order #123 costs $45", "XXX"), "Order #XXX costs $45"); assert_eq!(pattern.replace_all("Order #123 costs $45", "XXX"), "Order #XXX costs $XXX"); // Replacement with capture groups (NEW in v0.5.0) let swap = Pattern::new(r"(\w+)@(\w+)").unwrap(); assert_eq!(swap.replace("admin@example.com", "$2:$1"), "example:admin.com"); let fmt = Pattern::new(r"(\w+)=(\\d+)").unwrap(); assert_eq!(fmt.replace_all("a=1 b=2 c=3", "$1:[$2]"), "a:[1] b:[2] c:[3]"); // Text splitting (NEW in v0.5.0) let split = Pattern::new(r"\\s+").unwrap(); let parts: Vec<_> = split.split("a b c").collect(); assert_eq!(parts, vec!["a", "b", "c"]); // Anchors let exact = Pattern::new("^hello$").unwrap(); assert!(exact.is_match("hello")); assert!(!exact.is_match("hello world")); ``` -------------------------------- ### Recommended Production Setup Source: https://github.com/ksd-co/rexile/wiki/Configuration A comprehensive example of setting up ReXile patterns for production use, including static initialization and a struct to hold multiple patterns. ```rust use rexile::Pattern; use std::sync::OnceLock; use std::collections::HashMap; pub struct AppPatterns { email: Pattern, url: Pattern, ip: Pattern, log_level: Pattern, } impl AppPatterns { fn new() -> Self { Self { email: Pattern::new(r"^\w+@\w+\.\w+$").unwrap(), url: Pattern::new(r"^https?://[\w.-]+").unwrap(), ip: Pattern::new(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").unwrap(), log_level: Pattern::new(r"^\[(DEBUG|INFO|WARN|ERROR)\]").unwrap(), } } } static PATTERNS: OnceLock = OnceLock::new(); pub fn patterns() -> &'static AppPatterns { PATTERNS.get_or_init(AppPatterns::new) } // Usage fn validate_email(email: &str) -> bool { patterns().email.is_match(email) } ``` -------------------------------- ### Running Examples Source: https://github.com/ksd-co/rexile/blob/main/README.md Commands to run the provided examples from the ReXile crate. ```bash cargo run --example basic_usage cargo run --example log_processing ``` -------------------------------- ### Simple Matching Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Demonstrates basic pattern matching with ReXile. ```rust use rexile::ReXile; let pattern = ReXile::new(r"\d+").unwrap(); assert!(pattern.is_match("Order #12345")); ``` -------------------------------- ### Import Grouping Example Source: https://github.com/ksd-co/rexile/blob/main/AGENTS.md Example demonstrating the preferred grouping of imports. ```rust use std::fmt; use aho_corasick::AhoCorasick; use crate::parser::Sequence; ``` -------------------------------- ### Tips - Global Cache API Source: https://github.com/ksd-co/rexile/blob/main/examples/README.md Example demonstrating the use of the global cache API for automatic pattern caching. ```rust rexile::is_match(r"\w+@\w+", text).unwrap(); // Auto-cached ``` -------------------------------- ### Find Matches Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Shows how to find the first and all matches of a pattern. ```rust use rexile::Pattern; let pattern = Pattern::new(r"\d+").unwrap(); // Find first match if let Some((start, end)) = pattern.find("Item 123") { println!("Found at {}..{}", start, end); // Found at 5..8 } // Find all matches let matches = pattern.find_all("123 and 456"); // Returns: [(0, 3), (8, 11)] ``` -------------------------------- ### Anchored Patterns Example Source: https://github.com/ksd-co/rexile/blob/main/README.md Examples showing how to use anchors (^ for start, $ for end) to create patterns that match at specific positions within a string. ```rust // Must start with pattern let starts = Pattern::new("^Hello").unwrap(); assert!(starts.is_match("Hello World")); assert!(!starts.is_match("Say Hello")); // Must end with pattern let ends = Pattern::new("World$").unwrap(); assert!(ends.is_match("Hello World")); assert!(!ends.is_match("World Peace")); // Exact match let exact = Pattern::new("^exact$").unwrap(); assert!(exact.is_match("exact")); assert!(!exact.is_match("not exact")); ``` -------------------------------- ### Rust Toolchain Installation Source: https://github.com/ksd-co/rexile/blob/main/AGENTS.md Commands to install and set the Rust toolchain version. ```bash rustup install 1.70.0 rustup override set 1.70.0 ``` -------------------------------- ### Capture Groups Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Illustrates capturing groups from a pattern match. ```rust use rexile::Pattern; let pattern = Pattern::new(r"(\w+)@(\w+)\.(\w+)").unwrap(); if let Some(caps) = pattern.captures("admin@example.com") { println!("User: {:?}", caps.get(1)); // Some("admin") println!("Domain: {:?}", caps.get(2)); // Some("example") println!("TLD: {:?}", caps.get(3)); // Some("com") } ``` -------------------------------- ### Streaming Split Example Source: https://github.com/ksd-co/rexile/wiki/Advanced-Features An example demonstrating how to process large files line-by-line using a streaming split approach to avoid full allocation. ```rust let pattern = Pattern::new(r"\n").unwrap(); // Process large files line-by-line for line in pattern.split(&big_text) { process_line(line); // No full allocation } ``` -------------------------------- ### Pattern Library Example Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns An example demonstrating how to create a reusable pattern library for common regular expressions like email, URL, IP address, and date. ```rust use rexile::Pattern; use std::sync::OnceLock; pub struct Patterns { pub email: Pattern, pub url: Pattern, pub ip: Pattern, pub date: Pattern, } impl Patterns { pub fn new() -> Self { Self { email: Pattern::new(r"^\w+@\w+\.\w+$").unwrap(), url: Pattern::new(r"^https?://[\w.-]+").unwrap(), ip: Pattern::new(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").unwrap(), date: Pattern::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(), } } } static PATTERNS: OnceLock = OnceLock::new(); pub fn patterns() -> &'static Patterns { PATTERNS.get_or_init(Patterns::new) } // Usage if patterns().email.is_match(input) { // ... } ``` -------------------------------- ### Lookahead Example Source: https://github.com/ksd-co/rexile/wiki/Pattern-Syntax Example of using positive and negative lookahead assertions. ```rust // Match password requirements (8+ chars with digit and special char) let pattern = Pattern::new(r"(?=.*\d)(?=.*[!@#$])\w{8,}").unwrap(); assert!(pattern.is_match("Pass123!")); ``` -------------------------------- ### Specify Exact Version Source: https://github.com/ksd-co/rexile/wiki/Installation How to specify an exact version of ReXile in Cargo.toml. ```toml [dependencies] rexile = "0.4.7" # Exact version ``` -------------------------------- ### Performance Tip: Pre-compile Patterns Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Compares slow (compiling every time) vs. fast (compiling once) pattern usage. ```rust // ❌ Slow - compiles every time for line in lines { if ReXile::new(r"\d+").unwrap().is_match(line) { // ... } } // ✅ Fast - compile once, reuse many times let pattern = ReXile::new(r"\d+").unwrap(); for line in lines { if pattern.is_match(line) { // ... } } ``` -------------------------------- ### Performance Tip: Use Global Cache for One-Off Matches Source: https://github.com/ksd-co/rexile/wiki/Quick-Start Demonstrates using the globally cached function for one-off matches. ```rust // Automatically cached if rexile::is_match(r"\d+", text).unwrap() { // ... } ``` -------------------------------- ### Line Anchors Source: https://github.com/ksd-co/rexile/wiki/Pattern-Syntax Examples of using start-of-string and end-of-string anchors. ```rust // Line anchors let start = Pattern::new(r"^ERROR").unwrap(); assert!(start.is_match("ERROR: Failed")); let end = Pattern::new(r"failed$").unwrap(); assert!(end.is_match("Connection failed")); // Word boundaries let word = Pattern::new(r"\btest\b").unwrap(); assert!(word.is_match("run test now")); assert!(!word.is_match("testing")); ``` -------------------------------- ### Quick Example Source: https://github.com/ksd-co/rexile/wiki/Home Basic matching and capture group usage with the ReXile library. ```rust use rexile::{ReXile, Pattern}; // Basic matching let pattern = ReXile::new(r"\\w+@\\w+").unwrap(); assert!(pattern.is_match("user@domain")); // Capture groups let pattern = Pattern::new(r"(\\w+)@(\\w+)").unwrap(); if let Some(caps) = pattern.captures("admin@example") { println!("User: {:?}", caps.get(1)); // Some("admin") println!("Domain: {:?}", caps.get(2)); // Some("example") } ``` -------------------------------- ### Lookbehind Example Source: https://github.com/ksd-co/rexile/wiki/Pattern-Syntax Example of using positive and negative lookbehind assertions to extract price. ```rust // Extract price without currency symbol let pattern = Pattern::new(r"(?<=\$)\d+").unwrap(); if let Some((start, end)) = pattern.find("Price: $99") { // Extracts "99" without the "$" } ``` -------------------------------- ### Run Verification Test Source: https://github.com/ksd-co/rexile/wiki/Installation Command to run the verification test using cargo run. ```bash cargo run ``` -------------------------------- ### Custom Classes Source: https://github.com/ksd-co/rexile/wiki/Pattern-Syntax Examples of defining custom character classes in Rust. ```rust [abc] // Matches a, b, or c [a-z] // Lowercase letters [A-Z] // Uppercase letters [0-9] // Digits [a-zA-Z] // All letters [^abc] // Anything except a, b, c [^0-9] // Non-digits ``` ```rust let hex = Pattern::new(r"[0-9a-fA-F]+").unwrap(); assert!(hex.is_match("FF00CC")); let not_digit = Pattern::new(r"[^0-9]+").unwrap(); assert!(not_digit.is_match("abc")); ``` -------------------------------- ### Security Rules Examples Source: https://github.com/ksd-co/rexile/wiki/Rule-Engine-Integration Provides examples of adding rules for detecting SQL injection and Cross-Site Scripting (XSS) vulnerabilities. ```rust // SQL Injection detection engine.add_rule(Rule::new( "sql_injection", r"(?i)(union.*select|drop.*table)", 1, Box::new(|input| { // Block request false }), )?); // XSS detection engine.add_rule(Rule::new( "xss_detection", r"(?i) = pattern.split("a b c").collect(); assert_eq!(parts, vec!["a", "b", "c"]); // Split by comma let pattern = Pattern::new(r",\s*").unwrap(); let parts: Vec<_> = pattern.split("apple, banana,cherry").collect(); assert_eq!(parts, vec!["apple", "banana", "cherry"]); // Split by multiple delimiters let pattern = Pattern::new(r"[,;]").unwrap(); let parts: Vec<_> = pattern.split("a,b;c").collect(); assert_eq!(parts, vec!["a", "b", "c"]); ``` -------------------------------- ### Version Number Parsing Source: https://github.com/ksd-co/rexile/wiki/Production-Examples Parses version strings into major, minor, and patch components. ```rust let version_pattern = Pattern::new(r"v?(\d+)\.(\d+)\.?(\d*)").unwrap(); let versions = vec!["v1.2.3", "2.0", "v3.1.4"]; for version_str in versions { if let Some(caps) = version_pattern.captures(version_str) { let major = caps.get(1).unwrap().parse::().unwrap(); let minor = caps.get(2).unwrap().parse::().unwrap(); let patch = caps.get(3) .and_then(|s| if s.is_empty() { None } else { Some(s) }) .and_then(|s| s.parse::().ok()) .unwrap_or(0); println!("Version: {}.{}.{}", major, minor, patch); } } ``` -------------------------------- ### Dynamic Rule Loading Source: https://github.com/ksd-co/rexile/wiki/Production-Examples Loads rule configurations from a JSON file and compiles them into executable patterns. ```rust use serde::{Deserialize, Serialize}; #[derive(Deserialize)] struct RuleConfig { name: String, pattern: String, priority: u32, } fn load_rules(config_path: &str) -> Vec<(Pattern, u32)> { let config_str = std::fs::read_to_string(config_path).unwrap(); let configs: Vec = serde_json::from_str(&config_str).unwrap(); configs .into_iter() .filter_map(|cfg| { Pattern::new(&cfg.pattern) .ok() .map(|p| (p, cfg.priority)) }) .collect() } // rules.json: // [ // {"name": "error_check", "pattern": "(?i)error", "priority": 1}, // {"name": "warn_check", "pattern": "(?i)warn", "priority": 2} // ] ``` -------------------------------- ### Validation Rules Examples Source: https://github.com/ksd-co/rexile/wiki/Rule-Engine-Integration Illustrates how to add rules for validating email and phone number formats. ```rust // Email validation engine.add_rule(Rule::new( "email_format", r"^\w+@\w+\.\w+$", 1, Box::new(|_| true), )?); // Phone validation engine.add_rule(Rule::new( "phone_format", r"^\d{3}-\d{3}-\d{4}$", 1, Box::new(|_| true), )?); ``` -------------------------------- ### Alternation Example Source: https://github.com/ksd-co/rexile/wiki/Advanced-Features Demonstrates basic OR logic using the `|` operator to match one of several alternatives. ```Rust let pattern = Pattern::new(r"cat|dog|bird").unwrap(); assert!(pattern.is_match("I have a cat")); assert!(pattern.is_match("I have a dog")); ``` -------------------------------- ### Monitoring Performance Source: https://github.com/ksd-co/rexile/wiki/Rule-Engine-Integration Provides an example of how to measure the execution time of the rule engine. ```rust let start = Instant::now(); engine.execute_all(input); println!("Execution time: {:?}", start.elapsed()); ``` -------------------------------- ### URL Validation Source: https://github.com/ksd-co/rexile/wiki/Production-Examples Validates if a string conforms to a basic URL pattern. ```rust let url_pattern = Pattern::new(r"^(https?|ftp)://[^\s/$.?#].[^\s]*$").unwrap(); let urls = vec![ "https://example.com", "http://localhost:8080", "ftp://files.example.com", "not a url", ]; for url in urls { if url_pattern.is_match(url) { println!("Valid URL: {}", url); } } ``` -------------------------------- ### Add ReXile using cargo add Source: https://github.com/ksd-co/rexile/wiki/Installation Alternative method to add ReXile dependency using the cargo add command. ```bash cargo add rexile ``` -------------------------------- ### Condition Matching Source: https://github.com/ksd-co/rexile/wiki/Production-Examples Defines and evaluates rules based on regex patterns against input strings. ```rust use rexile::Pattern; struct Rule { name: String, pattern: Pattern, action: Box, } impl Rule { fn new(name: &str, pattern_str: &str, action: Box) -> Self { Rule { name: name.to_string(), pattern: Pattern::new(pattern_str).unwrap(), action, } } fn evaluate(&self, input: &str) -> bool { self.pattern.is_match(input) } fn execute(&self, input: &str) { (self.action)(input); } } // Usage let rules = vec![ Rule::new( "high_temp", r"temperature: (\d+)", Box::new(|input| { println!("High temperature alert: {}", input); }) ), Rule::new( "error_pattern", r"(?i)error|fail", Box::new(|input| { eprintln!("Error detected: {}", input); }) ), ]; for rule in &rules { if rule.evaluate("temperature: 95") { rule.execute("temperature: 95"); } } ``` -------------------------------- ### Variable Name Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Example for validating programming language variable names (starts with a letter or underscore). ```Rust // Programming language variable (starts with letter/underscore) let var_name = Pattern::new(r"^[a-zA-Z_]\w*$").unwrap(); assert!(var_name.is_match("my_variable")); assert!(var_name.is_match("_private")); assert!(!var_name.is_match("123invalid")); ``` -------------------------------- ### Pattern Storage with OnceLock Source: https://github.com/ksd-co/rexile/wiki/Configuration Example of using `std::sync::OnceLock` for efficient, thread-safe, one-time initialization of a static pattern. ```rust use std::sync::OnceLock; static EMAIL_PATTERN: OnceLock = OnceLock::new(); fn email_pattern() -> &'static Pattern { EMAIL_PATTERN.get_or_init(|| { Pattern::new(r"^\w+@\w+\.\w+$").unwrap() }) } ``` -------------------------------- ### Custom Pattern Cache Implementation Source: https://github.com/ksd-co/rexile/wiki/Configuration Provides an example of a custom `PatternCache` struct to manage pattern compilation and storage manually. ```rust use std::collections::HashMap; use rexile::Pattern; struct PatternCache { patterns: HashMap, } impl PatternCache { fn new() -> Self { PatternCache { patterns: HashMap::new(), } } fn get_or_compile(&mut self, pattern_str: &str) -> Result<&Pattern, Box> { if !self.patterns.contains_key(pattern_str) { let pattern = Pattern::new(pattern_str)?; self.patterns.insert(pattern_str.to_string(), pattern); } Ok(self.patterns.get(pattern_str).unwrap()) } } ``` -------------------------------- ### comprehensive.rs - All-in-One Demo Source: https://github.com/ksd-co/rexile/blob/main/examples/README.md Complete showcase of all ReXile features in a single file with menu-driven demos. Includes basic, advanced, performance, benchmark, and production use cases. ```bash cargo run --example comprehensive # All demos ``` ```bash cargo run --example comprehensive basic # Basic demo only ``` ```bash cargo run --example comprehensive advanced # Advanced features ``` ```bash cargo run --example comprehensive benchmark # 36 pattern benchmarks ``` -------------------------------- ### Pre-compiling Rules at Startup Source: https://github.com/ksd-co/rexile/wiki/Rule-Engine-Integration Demonstrates the best practice of pre-compiling and initializing the RuleEngine using `lazy_static` for efficient startup. ```rust lazy_static! { static ref ENGINE: RuleEngine = { let mut engine = RuleEngine::new(); // Load rules engine }; } ``` -------------------------------- ### perf_compare.rs - Performance Benchmarks Source: https://github.com/ksd-co/rexile/blob/main/examples/README.md Detailed performance comparison with the regex crate, covering test cases, memory usage, compile time, and ReXile-specific features. ```bash cargo run --release --example perf_compare ``` -------------------------------- ### Parse Escape Function Example Source: https://github.com/ksd-co/rexile/blob/main/ROADMAP_FULL_REGEX.md Example implementation for parsing escape sequences within a regex pattern. ```rust fn parse_escape(input: &str) -> Result { match input.chars().next() { Some('d') => Ok(Ast::CharClass { ranges: vec![('0', '9')], negated: false }), Some('w') => Ok(Ast::CharClass { ... }), Some('n') => Ok(Ast::Literal("\n".to_string())), // ... } } ``` -------------------------------- ### Literal Prefix Optimization Example Source: https://github.com/ksd-co/rexile/blob/main/ROADMAP_FULL_REGEX.md Illustrates a potential optimization for literal prefix matching in regex patterns. ```rust // Pattern: "hello.*world" // Fast path: memchr::find("hello"), then match rest ``` -------------------------------- ### Currency Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Example for validating dollar amounts. ```Rust // Dollar amount let currency = Pattern::new(r"^\$?\d{1,3}(,\d{3})*(\.\d{2})?$").unwrap(); assert!(currency.is_match("$1,234.56")); assert!(currency.is_match("999.99")); ``` -------------------------------- ### Basic Quantifiers Implementation (Week 2) Source: https://github.com/ksd-co/rexile/blob/main/ROADMAP_FULL_REGEX.md Example of implementing basic quantifier support (*, +, ?) in ReXile. ```rust // Goal: Support *, +, ? let pattern = Pattern::new("a+b*c?").unwrap(); assert!(pattern.is_match("aaabbc")); ``` -------------------------------- ### Nested Groups Source: https://github.com/ksd-co/rexile/wiki/Pattern-Syntax Example of nested capture groups. ```rust let pattern = Pattern::new(r"(((\w+)@(\w+)))").unwrap(); if let Some(caps) = pattern.captures("user@host") { // caps.get(1) = "user@host" // caps.get(2) = "user" // caps.get(3) = "host" } ``` -------------------------------- ### Integer Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Examples for validating positive and signed integers. ```Rust // Positive integer let positive_int = Pattern::new(r"^\d+$").unwrap(); assert!(positive_int.is_match("12345")); // Signed integer let signed_int = Pattern::new(r"^[+-]?\d+$").unwrap(); assert!(signed_int.is_match("-123")); assert!(signed_int.is_match("+456")); ``` -------------------------------- ### Alternation with Groups Source: https://github.com/ksd-co/rexile/wiki/Pattern-Syntax Example of using alternation with capture groups. ```rust let pattern = Pattern::new(r"cat|dog|bird").unwrap(); assert!(pattern.is_match("I have a cat")); assert!(pattern.is_match("I have a dog")); assert!(pattern.is_match("I have a bird")); // With groups let pattern = Pattern::new(r"(Mr|Ms|Dr)\. \w+").unwrap(); assert!(pattern.is_match("Dr. Smith")); ``` -------------------------------- ### Non-Capturing Groups Source: https://github.com/ksd-co/rexile/wiki/Pattern-Syntax Example of using non-capturing groups for efficiency. ```rust // Use (?:...) for grouping without capture overhead let pattern = Pattern::new(r"(?:https?|ftp)://\w+").unwrap(); assert!(pattern.is_match("https://example.com")); ``` -------------------------------- ### Use Anchors Source: https://github.com/ksd-co/rexile/wiki/Advanced-Features Demonstrates how using anchors can improve performance by failing faster. ```rust // ❌ Searches entire string Pattern::new(r"ERROR").unwrap() // ✅ Anchored - fails fast Pattern::new(r"^ERROR").unwrap() ``` -------------------------------- ### Scientific Notation Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Example for validating numbers in scientific notation. ```Rust let scientific = Pattern::new(r"^[+-]?\d+(\.\d+)?[eE][+-]?\d+$").unwrap(); assert!(scientific.is_match("1.23e-4")); assert!(scientific.is_match("-5E+10")); ``` -------------------------------- ### Basic Pattern Compilation Source: https://github.com/ksd-co/rexile/wiki/Configuration Demonstrates basic pattern creation in ReXile, which is automatically optimized. ```rust use rexile::Pattern; // Automatically optimized based on pattern let pattern = Pattern::new(r"\w+@\w+").unwrap(); ``` -------------------------------- ### URL Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Examples for validating HTTP/HTTPS URLs and capturing the protocol. ```Rust // HTTP/HTTPS let url = Pattern::new(r"^(https?://)?[\w.-]+\.\w+(/.*)?$").unwrap(); assert!(url.is_match("https://example.com")); assert!(url.is_match("example.com/path")); // With protocol capture let url_parts = Pattern::new(r"^(https?://)?([\w.-]+)(/.*)?$").unwrap(); ``` -------------------------------- ### Safe to Use - Quantifiers Source: https://github.com/ksd-co/rexile/blob/main/FEATURE_STATUS.md Examples of safe-to-use patterns with quantifiers. ```rust "\\w+" "\\d{2,}" // Use {n,} not {n,m} ``` -------------------------------- ### Manual Optimization: Use Appropriate Pattern Types Source: https://github.com/ksd-co/rexile/wiki/Configuration Demonstrates the performance difference between patterns with and without capture groups, and the benefit of non-capturing groups. ```rust // For validation (no captures) let validation = Pattern::new(r"\w+@\w+\.\w+").unwrap(); // ~45ns // For extraction (with captures) let extraction = Pattern::new(r"(\w+)@(\w+)\.(\w+)").unwrap(); // ~566ns // Use non-capturing when possible let optimized = Pattern::new(r"(?:\w+@\w+\.\w+)").unwrap(); // ~45ns ``` -------------------------------- ### Environment-Specific Pattern Initialization Source: https://github.com/ksd-co/rexile/wiki/Configuration Demonstrates how to initialize different sets of patterns based on whether the application is running in debug or release mode. ```rust #[cfg(debug_assertions)] fn init_patterns() -> Vec { // Development: more verbose patterns for debugging vec![ Pattern::new(r"DEBUG: (.+)").unwrap(), // ... ] } #[cfg(not(debug_assertions))] fn init_patterns() -> Vec { // Production: optimized patterns vec![ Pattern::new(r"(?:DEBUG|INFO|WARN|ERROR): (.+)").unwrap(), // ... ] } ``` -------------------------------- ### Run benchmarks yourself Source: https://github.com/ksd-co/rexile/blob/main/README.md Commands to run the performance benchmarks for ReXile. ```bash cargo run --release --example per_file_grl_benchmark cargo run --release --example memory_comparison ``` -------------------------------- ### Username Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Example for validating usernames (alphanumeric + underscore, 3-16 characters). ```Rust // Alphanumeric + underscore, 3-16 chars let username = Pattern::new(r"^\w{3,16}$").unwrap(); assert!(username.is_match("user_123")); assert!(!username.is_match("ab")); // Too short ``` -------------------------------- ### Real-World Example: Log Processing Rules Source: https://github.com/ksd-co/rexile/wiki/Rule-Engine-Integration Demonstrates how to use the `RuleEngine` to process log entries. It defines rules for error detection, warning detection, and performance monitoring, then iterates through a list of logs, executing the appropriate actions. ```rust let mut engine = RuleEngine::new(); // Rule 1: Error detection (highest priority) engine.add_rule(Rule::new( "error_detection", r"(?i)(error|fail|exception)", 1, Box::new(|input| { eprintln!("ERROR: {}", input); true }), )?); // Rule 2: Warning detection engine.add_rule(Rule::new( "warning_detection", r"(?i)warn", 2, Box::new(|input| { println!("WARNING: {}", input); true }), )?); // Rule 3: Performance monitoring engine.add_rule(Rule::new( "slow_query", r"query took (\d+)ms", 3, Box::new(|input| { // Extract duration and check threshold true }), )?); // Process logs let logs = vec![ "[ERROR] Database connection failed", "[WARN] High memory usage", "[INFO] Query took 150ms", ]; for log in logs { engine.execute_all(log); } ``` -------------------------------- ### Time Format Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Examples for validating 24-hour and 12-hour time formats. ```Rust // 24-hour: HH:MM:SS let time_24 = Pattern::new(r"^\d{2}:\d{2}:\d{2}$").unwrap(); assert!(time_24.is_match("14:30:45")); // 12-hour: HH:MM AM/PM let time_12 = Pattern::new(r"^\d{1,2}:\d{2}\s?(AM|PM)$").unwrap(); assert!(time_12.is_match("2:30 PM")); ``` -------------------------------- ### Phone Number Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Example for validating US phone number formats. ```Rust // US format: (123) 456-7890 or 123-456-7890 let phone = Pattern::new(r"^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$").unwrap(); assert!(phone.is_match("(123) 456-7890")); assert!(phone.is_match("123-456-7890")); ``` -------------------------------- ### Build Commands Source: https://github.com/ksd-co/rexile/blob/main/AGENTS.md Common cargo commands for building the project in debug and release modes. ```bash cargo build --verbose cargo build --release --verbose ``` -------------------------------- ### Quick Benchmark Source: https://github.com/ksd-co/rexile/wiki/Home A quick benchmark comparing ReXile to the regex crate for various pattern types, compile time, and memory usage. ```text Pattern Type ReXile Regex Speedup ───────────────────────────────────────────────── Literal (ERROR) 27ns 29ns 1.1x faster Word chars (\w+) 22ns 106ns 4.8x faster Char class [a-z]+ 11ns 30ns 2.7x faster Email (\w+@\w+) 37ns 107ns 2.9x faster Compile time 21Ξs 435Ξs 20.9x faster Memory usage 896KB 2488KB 2.8x less ``` -------------------------------- ### Safe to Use - Lookahead Source: https://github.com/ksd-co/rexile/blob/main/FEATURE_STATUS.md Examples of safe-to-use patterns with lookahead assertions. ```rust "\\w+(?=:)" // Word before colon "password(?!123)" // Password not followed by 123 ``` -------------------------------- ### Date Format Validation Source: https://github.com/ksd-co/rexile/wiki/Production-Examples Validates and parses date strings in YYYY-MM-DD format. ```rust let date_pattern = Pattern::new(r"^(\d{4})-(\d{2})-(\d{2})$").unwrap(); fn parse_date(date_str: &str) -> Option<(u32, u32, u32)> { date_pattern.captures(date_str).and_then(|caps| { let year = caps.get(1)?.parse().ok()?; let month = caps.get(2)?.parse().ok()?; let day = caps.get(3)?.parse().ok()?; Some((year, month, day)) }) } assert_eq!(parse_date("2024-01-15"), Some((2024, 1, 15))); assert_eq!(parse_date("not-a-date"), None); ``` -------------------------------- ### Run Benchmarks Source: https://github.com/ksd-co/rexile/wiki/Contributing Command to run project benchmarks. ```bash cargo bench ``` -------------------------------- ### Email Extraction and Validation Source: https://github.com/ksd-co/rexile/wiki/Production-Examples Extracts and validates email addresses from a given text. ```rust let email_pattern = Pattern::new(r"(\w+)@(\w+\.\w+)").unwrap(); let text = "Contact: admin@example.com, support@test.org"; for (start, end) in email_pattern.find_all(text) { let email = &text[start..end]; if let Some(caps) = email_pattern.captures(email) { let user = caps.get(1).unwrap(); let domain = caps.get(2).unwrap(); println!("Email: {} (user: {}, domain: {})", email, user, domain); } } ``` -------------------------------- ### Safe to Use - Anchored patterns Source: https://github.com/ksd-co/rexile/blob/main/FEATURE_STATUS.md Examples of safe-to-use patterns with anchors. ```rust "^GET " "\\.$" ``` -------------------------------- ### Character Classes Implementation (Week 1) Source: https://github.com/ksd-co/rexile/blob/main/ROADMAP_FULL_REGEX.md Example of implementing character class support in ReXile. ```rust // Goal: Support [a-z], [0-9], [^abc] let pattern = Pattern::new("[a-z]+").unwrap(); assert!(pattern.is_match("hello")); ``` -------------------------------- ### Quick Benchmark Source: https://github.com/ksd-co/rexile/wiki/Performance A basic Rust code snippet to benchmark the performance of a single ReXile pattern over multiple iterations. ```rust use std::time::Instant; use rexile::Pattern; let pattern = Pattern::new(r"your_pattern").unwrap(); let text = "your test text"; let start = Instant::now(); for _ in 0..10_000 { pattern.is_match(text); } let elapsed = start.elapsed(); println!("Average: {:?}", elapsed / 10_000); ``` -------------------------------- ### Wrapping the 'regex' Crate API Source: https://github.com/ksd-co/rexile/blob/main/ROADMAP_FULL_REGEX.md Example of creating a wrapper struct around the 'regex' crate to provide a simpler API. ```rust pub struct Pattern { inner: regex::Regex, } impl Pattern { pub fn new(pattern: &str) -> Result { Ok(Pattern { inner: regex::Regex::new(pattern) .map_err(|e| PatternError::ParseError(e.to_string()))?, }) } // Simpler API on top of regex } ``` -------------------------------- ### Decimal Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Examples for validating decimal numbers and numbers with optional decimal parts. ```Rust // Decimal number let decimal = Pattern::new(r"^[+-]?\d+\.\d+$").unwrap(); assert!(decimal.is_match("3.14")); assert!(decimal.is_match("-0.5")); // Optional decimal let opt_decimal = Pattern::new(r"^[+-]?\d+(\.\d+)?$").unwrap(); assert!(opt_decimal.is_match("42")); assert!(opt_decimal.is_match("3.14")); ``` -------------------------------- ### Timestamp Validation Source: https://github.com/ksd-co/rexile/wiki/Common-Patterns Examples for validating full timestamps and ISO 8601 timestamps with timezones. ```Rust // Full timestamp: YYYY-MM-DD HH:MM:SS let timestamp = Pattern::new(r"^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$").unwrap(); assert!(timestamp.is_match("2024-01-15 14:30:45")); // ISO 8601 with timezone let iso_timestamp = Pattern::new(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$").unwrap(); assert!(iso_timestamp.is_match("2024-01-15T14:30:45+00:00")); ```