easy_regex/head_or_tail.rs
1//! Includes methods for starting/ending chain of expressions.
2//!
3//! This module includes methods typically useful to start or end a regular expression.
4//! Methods as [`start_of_line`](../struct.EasyRegex.html#method.start_of_line), [`only_the_beginning`](../struct.EasyRegex.html#method.only_the_beginning)
5//! and flag-related methods can only be used as the starting method and
6//! the others could be used in the middle or at the end of a method chain as well.
7
8use crate::EasyRegex;
9
10impl EasyRegex {
11 /// Creates an ```EasyRegex``` instance starting with the ```^``` character, asserts position at start of the string.
12 pub fn start_of_line() -> Self {
13 EasyRegex("^".to_string())
14 }
15
16 /// Adds the alternation symbol ```|``` to the expression.
17 pub fn or(self) -> Self {
18 let result = format!("{}|", self.0);
19 EasyRegex(result)
20 }
21
22 /// Creates a list having ```^``` at the beginning.
23 ///
24 /// # Examples
25 ///
26 /// ```
27 /// use easy_regex::EasyRegex;
28 ///
29 /// let result = EasyRegex::new_section().not("abc");
30 /// assert_eq!("[^abc]", result.get_regex().unwrap().as_str());
31 /// ```
32 pub fn not(self, expression: &str) -> Self {
33 let result = format!("{}[^{}]", self.0, expression);
34 EasyRegex(result)
35 }
36
37 /// Adds one space character i.e. " " to the previous expression.
38 pub fn literal_space(self) -> Self {
39 let result = format!("{} ", self.0);
40 EasyRegex(result)
41 }
42
43 /// Adds the ending pattern ```$```, asserts position at the end of the string.
44 pub fn end_of_line(self) -> Self {
45 let result = format!("{}$", self.0);
46 EasyRegex(result)
47 }
48
49 /// Creates an ```EasyRegex``` instance starting with the ```(?i)``` flag.
50 pub fn insensitive() -> Self {
51 EasyRegex("(?i)".to_string())
52 }
53
54 /// Creates an ```EasyRegex``` instance starting with the ```(?m)``` flag.
55 pub fn multiline() -> Self {
56 EasyRegex("(?m)".to_string())
57 }
58
59 /// Creates an ```EasyRegex``` instance starting with the ```(?s)``` flag.
60 pub fn dot_match_newline() -> Self {
61 EasyRegex("(?s)".to_string())
62 }
63
64 /// Creates an ```EasyRegex``` instance starting with the ```(?x)``` flag.
65 pub fn ignore_whitespace() -> Self {
66 EasyRegex("(?x)".to_string())
67 }
68}
69
70#[cfg(test)]
71mod tests {
72 use crate::{EasyRegex, settings::base::DEFAULT};
73
74 #[test]
75 fn end_of_line_works() {
76 let result = EasyRegex::new("abc").end_of_line();
77 assert_eq!("abc$", result.0);
78 }
79
80 #[test]
81 fn or_works() {
82 let result = EasyRegex::new_section()
83 .literal("abc", &DEFAULT)
84 .or()
85 .literal("efg", &DEFAULT)
86 .into_list(&DEFAULT);
87 assert_eq!("[abc|efg]", result.0);
88 }
89}