Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ mod traits;
mod r#type;

pub use r#type::{not, Input, Input::*, Type, Type::*};
pub use traits::{AsRegex, Condition, Error, Result};
pub use traits::{AsRegex, Condition, Error, Grouping, Result};
52 changes: 52 additions & 0 deletions src/core/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,55 @@ pub trait Condition: AsRegex + Sized {
Regex::new(&format!("(?:{})?", self.to_string())).expect("Invalid regex (optionally)")
}
}

pub trait Grouping: AsRegex {
/// This defines the entire input so far as a named capture group.
///
/// # Example
/// ```
/// use magic_regexp::{create_reg_exp, Condition,Grouping, Digit, LetterLowercase, OneOrMore};
///
/// let regex = create_reg_exp(OneOrMore(Digit).grouped_as("digits")).unwrap();
/// assert_eq!(&regex.captures("1").unwrap()["digits"], "1");
/// ```
fn grouped_as(&self, name: &str) -> Regex {
Regex::new(&format!(r"(?P<{}>{})", name, self.to_string())).expect("Invalid regex")
}

/// This defines the entire input so far as a named capture group.
/// This is an alias for `grouped_as`.
fn r#as(&self, name: &str) -> Regex {
self.grouped_as(name)
}

/// This defines the entire input so far as an anonymous group.
///
/// # Example
/// ```
/// use magic_regexp::{create_reg_exp, Condition, Grouping, Digit, LetterLowercase, OneOrMore, Type, Char, Whitespace, Maybe};
/// use regex::Regex;
///
/// let regex = create_reg_exp(OneOrMore(Digit).grouped()
/// .and(Whitespace)
/// .and(OneOrMore(Char).or(Whitespace).optionally())
/// .and(OneOrMore(Digit).grouped())
/// ).unwrap();
/// assert_eq!(&regex.captures("1 5").unwrap()[1], "1");
/// assert_eq!(&regex.captures("134 23").unwrap()[1], "134");
/// // The folloing example is not really useful, because it shows only the first match.
/// // The second match is not captured. See the next example for a more useful example.
/// assert_eq!(&regex.captures("this is the 134 test 213").unwrap()[1], "134");
/// // This is a bit more complex, because we are using anonymous groups in regex.
/// let cap = &regex
/// .find_iter("multiple numbers 134 2123")
/// .filter_map(|digits| digits.as_str().parse().ok())
/// .collect::<Vec<String>>()
/// .join(" ");
/// let expected = ["134", "2123"].join(" ");
/// assert_eq!(cap, &expected);
/// ```
///
fn grouped(&self) -> Regex {
Regex::new(&format!(r"({})", self.to_string())).expect("Invalid regex")
}
}
Loading