Struct LuaPattern

Source
pub struct LuaPattern<'a> { /* private fields */ }
Expand description

Represents a Lua string pattern and the results of a match

Implementations§

Source§

impl<'a> LuaPattern<'a>

Source

pub fn from_bytes_try(bytes: &'a [u8]) -> Result<LuaPattern<'a>, PatternError>

Maybe create a new Lua pattern from a slice of bytes

Source

pub fn new_try(patt: &'a str) -> Result<LuaPattern<'a>, PatternError>

Maybe create a new Lua pattern from a string

Examples found in repository?
examples/errors.rs (line 19)
4fn main() {
5    let bad = [
6        ("bonzo %", "malformed pattern (ends with '%')"),
7        ("bonzo (dog%(", "unfinished capture"),
8        ("alles [%a%[", "malformed pattern (missing ']')"),
9        ("bonzo (dog (cat)", "unfinished capture"),
10        ("frodo %f[%A", "malformed pattern (missing ']')"),
11        ("frodo (1) (2(3)%2)%1", "invalid capture index %2"),
12    ];
13
14    fn error(s: &str) -> PatternError {
15        PatternError::Pattern(s.into())
16    }
17
18    for p in bad.iter() {
19        let res = lua_patterns::LuaPattern::new_try(p.0);
20        if let Err(e) = res {
21            assert_eq!(e, error(p.1));
22        } else {
23            println!("'{}' was fine", p.0);
24        }
25    }
26}
Source

pub fn new(patt: &'a str) -> LuaPattern<'a>

Create a new Lua pattern from a string, panicking if bad

Examples found in repository?
examples/multiple_captures.rs (line 4)
3fn main() {
4    let mut p = lp::LuaPattern::new("%s*(%d+)%s+(%S+)");
5    if let Some((int, rest)) = p.match_maybe_2(" 233   hello dolly") {
6        assert_eq!(int, "233");
7        assert_eq!(rest, "hello");
8    }
9}
More examples
Hide additional examples
examples/strings.rs (line 17)
11fn main() {
12    let file = env::args().skip(1).next().expect("provide a binary file");
13    let mut f = File::open(&file).expect("can't open file");
14    let mut buf = Vec::new();
15    f.read_to_end(&mut buf).expect("can't read file");
16
17    let mut words = LuaPattern::new("%a%a%a%a+");
18    for w in words.gmatch_bytes(&buf) {
19        println!("{}", str::from_utf8(w).unwrap());
20    }
21}
examples/range.rs (line 5)
4fn main() {
5    let mut m = LuaPattern::new("(%a+) one");
6    let text = " hello one two";
7    assert!(m.matches(text));
8    assert_eq!(m.capture(1), 1..6);
9    assert_eq!(m.capture(0), 1..10);
10
11    let v = m.captures(text);
12    assert_eq!(v, &["hello one", "hello"]);
13
14    let mut v = Vec::new();
15    assert!(m.capture_into(text, &mut v));
16    assert_eq!(v, &["hello one", "hello"]);
17
18    let bytes = &[0xFF, 0xEE, 0x0, 0xDE, 0x24, 0x24, 0xBE, 0x0, 0x0];
19
20    let patt = LuaPatternBuilder::new()
21        .bytes_as_hex("DE24")
22        .text("+")
23        .bytes(&[0xBE])
24        .build();
25
26    let mut m = LuaPattern::from_bytes(&patt);
27    assert!(m.matches_bytes(bytes));
28    assert_eq!(&bytes[m.capture(0)], &[0xDE, 0x24, 0x24, 0xBE]);
29
30    let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
31    let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
32    println!("{}", res);
33
34    let mut m = LuaPattern::new("%s+");
35    let res = m.gsub("hello dolly you're so fine", "");
36    println!("{}", res);
37}
examples/iter.rs (line 8)
3fn main() {
4    //~ let mut m = lp::LuaPattern::new("hello%");
5    //~ m.matches("hello");
6    //~ println!("ok");
7
8    let mut m = lp::LuaPattern::new("(%a+)");
9    let mut iter = m.gmatch("one two three");
10    assert_eq!(iter.next(), Some("one"));
11    assert_eq!(iter.next(), Some("two"));
12    assert_eq!(iter.next(), Some("three"));
13    assert_eq!(iter.next(), None);
14
15    let mut m = lp::LuaPattern::new("%S+");
16    let split: Vec<_> = m.gmatch("dog  cat leopard wolf").collect();
17    assert_eq!(split, &["dog", "cat", "leopard", "wolf"]);
18
19    let mut m = lp::LuaPattern::new("%s*(%S+)%s*=%s*(.-);");
20    let cc = m.captures(" hello= bonzo dog;");
21    assert_eq!(cc[0], " hello= bonzo dog;");
22    assert_eq!(cc[1], "hello");
23    assert_eq!(cc[2], "bonzo dog");
24
25    for cc in m.gmatch_captures("hello=bonzo dog; bye=cat;") {
26        println!("'{}'='{}'", cc.get(1), cc.get(2));
27    }
28
29    let mut m = lp::LuaPattern::new("%$(%S+)");
30    let res = m.gsub_with("hello $dolly you're so $fine", |cc| {
31        cc.get(1).to_uppercase()
32    });
33    assert_eq!(res, "hello DOLLY you're so FINE");
34
35    let mut m = lp::LuaPattern::new("(%S+)%s*=%s*([^;]+);");
36    let res = m.gsub_with("alpha=bonzo; beta=felix;", |cc| {
37        format!("{}:'{}',", cc.get(1), cc.get(2))
38    });
39    assert_eq!(res, "alpha:'bonzo', beta:'felix',");
40}
Source

pub fn from_bytes(bytes: &'a [u8]) -> LuaPattern<'a>

Create a new Lua pattern from a slice of bytes, panicking if bad

Examples found in repository?
examples/range.rs (line 26)
4fn main() {
5    let mut m = LuaPattern::new("(%a+) one");
6    let text = " hello one two";
7    assert!(m.matches(text));
8    assert_eq!(m.capture(1), 1..6);
9    assert_eq!(m.capture(0), 1..10);
10
11    let v = m.captures(text);
12    assert_eq!(v, &["hello one", "hello"]);
13
14    let mut v = Vec::new();
15    assert!(m.capture_into(text, &mut v));
16    assert_eq!(v, &["hello one", "hello"]);
17
18    let bytes = &[0xFF, 0xEE, 0x0, 0xDE, 0x24, 0x24, 0xBE, 0x0, 0x0];
19
20    let patt = LuaPatternBuilder::new()
21        .bytes_as_hex("DE24")
22        .text("+")
23        .bytes(&[0xBE])
24        .build();
25
26    let mut m = LuaPattern::from_bytes(&patt);
27    assert!(m.matches_bytes(bytes));
28    assert_eq!(&bytes[m.capture(0)], &[0xDE, 0x24, 0x24, 0xBE]);
29
30    let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
31    let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
32    println!("{}", res);
33
34    let mut m = LuaPattern::new("%s+");
35    let res = m.gsub("hello dolly you're so fine", "");
36    println!("{}", res);
37}
Source

pub fn matches_bytes(&mut self, s: &[u8]) -> bool

Match a slice of bytes with a pattern

let patt = &[0xFE,0xEE,b'+',0xED];
let mut m = lua_patterns::LuaPattern::from_bytes(patt);
let bytes = &[0x00,0x01,0xFE,0xEE,0xEE,0xED,0xEF];
assert!(m.matches_bytes(bytes));
assert_eq!(&bytes[m.range()], &[0xFE,0xEE,0xEE,0xED]);
Examples found in repository?
examples/range.rs (line 27)
4fn main() {
5    let mut m = LuaPattern::new("(%a+) one");
6    let text = " hello one two";
7    assert!(m.matches(text));
8    assert_eq!(m.capture(1), 1..6);
9    assert_eq!(m.capture(0), 1..10);
10
11    let v = m.captures(text);
12    assert_eq!(v, &["hello one", "hello"]);
13
14    let mut v = Vec::new();
15    assert!(m.capture_into(text, &mut v));
16    assert_eq!(v, &["hello one", "hello"]);
17
18    let bytes = &[0xFF, 0xEE, 0x0, 0xDE, 0x24, 0x24, 0xBE, 0x0, 0x0];
19
20    let patt = LuaPatternBuilder::new()
21        .bytes_as_hex("DE24")
22        .text("+")
23        .bytes(&[0xBE])
24        .build();
25
26    let mut m = LuaPattern::from_bytes(&patt);
27    assert!(m.matches_bytes(bytes));
28    assert_eq!(&bytes[m.capture(0)], &[0xDE, 0x24, 0x24, 0xBE]);
29
30    let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
31    let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
32    println!("{}", res);
33
34    let mut m = LuaPattern::new("%s+");
35    let res = m.gsub("hello dolly you're so fine", "");
36    println!("{}", res);
37}
Source

pub fn matches(&mut self, text: &str) -> bool

Match a string with a pattern

let mut m = lua_patterns::LuaPattern::new("(%a+) one");
let text = " hello one two";
assert!(m.matches(text));
Examples found in repository?
examples/range.rs (line 7)
4fn main() {
5    let mut m = LuaPattern::new("(%a+) one");
6    let text = " hello one two";
7    assert!(m.matches(text));
8    assert_eq!(m.capture(1), 1..6);
9    assert_eq!(m.capture(0), 1..10);
10
11    let v = m.captures(text);
12    assert_eq!(v, &["hello one", "hello"]);
13
14    let mut v = Vec::new();
15    assert!(m.capture_into(text, &mut v));
16    assert_eq!(v, &["hello one", "hello"]);
17
18    let bytes = &[0xFF, 0xEE, 0x0, 0xDE, 0x24, 0x24, 0xBE, 0x0, 0x0];
19
20    let patt = LuaPatternBuilder::new()
21        .bytes_as_hex("DE24")
22        .text("+")
23        .bytes(&[0xBE])
24        .build();
25
26    let mut m = LuaPattern::from_bytes(&patt);
27    assert!(m.matches_bytes(bytes));
28    assert_eq!(&bytes[m.capture(0)], &[0xDE, 0x24, 0x24, 0xBE]);
29
30    let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
31    let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
32    println!("{}", res);
33
34    let mut m = LuaPattern::new("%s+");
35    let res = m.gsub("hello dolly you're so fine", "");
36    println!("{}", res);
37}
Source

pub fn match_maybe<'t>(&mut self, text: &'t str) -> Option<&'t str>

Match a string, returning first capture if successful

let mut m = lua_patterns::LuaPattern::new("OK%s+(%d+)");
let res = m.match_maybe("and that's OK 400 to you");
assert_eq!(res, Some("400"));
Source

pub fn match_maybe_2<'t>(&mut self, text: &'t str) -> Option<(&'t str, &'t str)>

Match a string, returning first two explicit captures if successful

let mut p = lua_patterns::LuaPattern::new("%s*(%d+)%s+(%S+)");
let (int,rest) = p.match_maybe_2(" 233   hello dolly").unwrap();
assert_eq!(int,"233");
assert_eq!(rest,"hello");
Examples found in repository?
examples/multiple_captures.rs (line 5)
3fn main() {
4    let mut p = lp::LuaPattern::new("%s*(%d+)%s+(%S+)");
5    if let Some((int, rest)) = p.match_maybe_2(" 233   hello dolly") {
6        assert_eq!(int, "233");
7        assert_eq!(rest, "hello");
8    }
9}
Source

pub fn match_maybe_3<'t>( &mut self, text: &'t str, ) -> Option<(&'t str, &'t str, &'t str)>

Match a string, returning first three explicit captures if successful

let mut p = lua_patterns::LuaPattern::new("(%d+)/(%d+)/(%d+)");
let (y,m,d) = p.match_maybe_3("2017/11/10").unwrap();
assert_eq!(y,"2017");
assert_eq!(m,"11");
assert_eq!(d,"10");
Source

pub fn match_maybe_4<'t>( &mut self, text: &'t str, ) -> Option<(&'t str, &'t str, &'t str, &'t str)>

Match a string, returning first four explicit captures if successful

let mut p = lua_patterns::LuaPattern::new("(%d+)/(%d+)/(%d+):(%S+)");
let (y,m,d,r) = p.match_maybe_4("2017/11/10:rest").unwrap();
assert_eq!(y,"2017");
assert_eq!(m,"11");
assert_eq!(d,"10");
assert_eq!(r,"rest");
Source

pub fn captures<'b>(&mut self, text: &'b str) -> Vec<&'b str>

Match and collect all captures as a vector of string slices

let mut m = lua_patterns::LuaPattern::new("(one).+");
assert_eq!(m.captures(" one two"), &["one two","one"]);
Examples found in repository?
examples/range.rs (line 11)
4fn main() {
5    let mut m = LuaPattern::new("(%a+) one");
6    let text = " hello one two";
7    assert!(m.matches(text));
8    assert_eq!(m.capture(1), 1..6);
9    assert_eq!(m.capture(0), 1..10);
10
11    let v = m.captures(text);
12    assert_eq!(v, &["hello one", "hello"]);
13
14    let mut v = Vec::new();
15    assert!(m.capture_into(text, &mut v));
16    assert_eq!(v, &["hello one", "hello"]);
17
18    let bytes = &[0xFF, 0xEE, 0x0, 0xDE, 0x24, 0x24, 0xBE, 0x0, 0x0];
19
20    let patt = LuaPatternBuilder::new()
21        .bytes_as_hex("DE24")
22        .text("+")
23        .bytes(&[0xBE])
24        .build();
25
26    let mut m = LuaPattern::from_bytes(&patt);
27    assert!(m.matches_bytes(bytes));
28    assert_eq!(&bytes[m.capture(0)], &[0xDE, 0x24, 0x24, 0xBE]);
29
30    let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
31    let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
32    println!("{}", res);
33
34    let mut m = LuaPattern::new("%s+");
35    let res = m.gsub("hello dolly you're so fine", "");
36    println!("{}", res);
37}
More examples
Hide additional examples
examples/iter.rs (line 20)
3fn main() {
4    //~ let mut m = lp::LuaPattern::new("hello%");
5    //~ m.matches("hello");
6    //~ println!("ok");
7
8    let mut m = lp::LuaPattern::new("(%a+)");
9    let mut iter = m.gmatch("one two three");
10    assert_eq!(iter.next(), Some("one"));
11    assert_eq!(iter.next(), Some("two"));
12    assert_eq!(iter.next(), Some("three"));
13    assert_eq!(iter.next(), None);
14
15    let mut m = lp::LuaPattern::new("%S+");
16    let split: Vec<_> = m.gmatch("dog  cat leopard wolf").collect();
17    assert_eq!(split, &["dog", "cat", "leopard", "wolf"]);
18
19    let mut m = lp::LuaPattern::new("%s*(%S+)%s*=%s*(.-);");
20    let cc = m.captures(" hello= bonzo dog;");
21    assert_eq!(cc[0], " hello= bonzo dog;");
22    assert_eq!(cc[1], "hello");
23    assert_eq!(cc[2], "bonzo dog");
24
25    for cc in m.gmatch_captures("hello=bonzo dog; bye=cat;") {
26        println!("'{}'='{}'", cc.get(1), cc.get(2));
27    }
28
29    let mut m = lp::LuaPattern::new("%$(%S+)");
30    let res = m.gsub_with("hello $dolly you're so $fine", |cc| {
31        cc.get(1).to_uppercase()
32    });
33    assert_eq!(res, "hello DOLLY you're so FINE");
34
35    let mut m = lp::LuaPattern::new("(%S+)%s*=%s*([^;]+);");
36    let res = m.gsub_with("alpha=bonzo; beta=felix;", |cc| {
37        format!("{}:'{}',", cc.get(1), cc.get(2))
38    });
39    assert_eq!(res, "alpha:'bonzo', beta:'felix',");
40}
Source

pub fn match_captures<'b, 'c>(&'c self, text: &'b str) -> Captures<'a, 'b, 'c>

A convenient way to access the captures with no allocation

let text = "  hello one";
let mut m = lua_patterns::LuaPattern::new("(%S+) one");
if m.matches(text) {
    let cc = m.match_captures(text);
    assert_eq!(cc.get(0), "hello one");
    assert_eq!(cc.get(1), "hello");
}

The result is also an iterator over the captures:

let text = "  hello one";
let mut m = lua_patterns::LuaPattern::new("(%S+) one");
if m.matches(text) {
    let mut iter = m.match_captures(text);
    assert_eq!(iter.next(), Some("hello one"));
    assert_eq!(iter.next(), Some("hello"));
}
Source

pub fn capture_into<'b>( &mut self, text: &'b str, vec: &mut Vec<&'b str>, ) -> bool

Match and collect all captures into the provided vector.

let text = "  hello one";
let mut m = lua_patterns::LuaPattern::new("(%S+) one");
let mut v = Vec::new();
if m.capture_into(text,&mut v) {
    assert_eq!(v, &["hello one","hello"]);
}
Examples found in repository?
examples/range.rs (line 15)
4fn main() {
5    let mut m = LuaPattern::new("(%a+) one");
6    let text = " hello one two";
7    assert!(m.matches(text));
8    assert_eq!(m.capture(1), 1..6);
9    assert_eq!(m.capture(0), 1..10);
10
11    let v = m.captures(text);
12    assert_eq!(v, &["hello one", "hello"]);
13
14    let mut v = Vec::new();
15    assert!(m.capture_into(text, &mut v));
16    assert_eq!(v, &["hello one", "hello"]);
17
18    let bytes = &[0xFF, 0xEE, 0x0, 0xDE, 0x24, 0x24, 0xBE, 0x0, 0x0];
19
20    let patt = LuaPatternBuilder::new()
21        .bytes_as_hex("DE24")
22        .text("+")
23        .bytes(&[0xBE])
24        .build();
25
26    let mut m = LuaPattern::from_bytes(&patt);
27    assert!(m.matches_bytes(bytes));
28    assert_eq!(&bytes[m.capture(0)], &[0xDE, 0x24, 0x24, 0xBE]);
29
30    let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
31    let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
32    println!("{}", res);
33
34    let mut m = LuaPattern::new("%s+");
35    let res = m.gsub("hello dolly you're so fine", "");
36    println!("{}", res);
37}
Source

pub fn range(&self) -> Range<usize>

The full match (same as capture(0))

Source

pub fn capture(&self, i: usize) -> Range<usize>

Get the nth capture of the match.

let mut m = lua_patterns::LuaPattern::new("(%a+) one");
let text = " hello one two";
assert!(m.matches(text));
assert_eq!(m.capture(0),1..10);
assert_eq!(m.capture(1),1..6);
Examples found in repository?
examples/range.rs (line 8)
4fn main() {
5    let mut m = LuaPattern::new("(%a+) one");
6    let text = " hello one two";
7    assert!(m.matches(text));
8    assert_eq!(m.capture(1), 1..6);
9    assert_eq!(m.capture(0), 1..10);
10
11    let v = m.captures(text);
12    assert_eq!(v, &["hello one", "hello"]);
13
14    let mut v = Vec::new();
15    assert!(m.capture_into(text, &mut v));
16    assert_eq!(v, &["hello one", "hello"]);
17
18    let bytes = &[0xFF, 0xEE, 0x0, 0xDE, 0x24, 0x24, 0xBE, 0x0, 0x0];
19
20    let patt = LuaPatternBuilder::new()
21        .bytes_as_hex("DE24")
22        .text("+")
23        .bytes(&[0xBE])
24        .build();
25
26    let mut m = LuaPattern::from_bytes(&patt);
27    assert!(m.matches_bytes(bytes));
28    assert_eq!(&bytes[m.capture(0)], &[0xDE, 0x24, 0x24, 0xBE]);
29
30    let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
31    let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
32    println!("{}", res);
33
34    let mut m = LuaPattern::new("%s+");
35    let res = m.gsub("hello dolly you're so fine", "");
36    println!("{}", res);
37}
Source

pub fn first_capture(&self) -> Range<usize>

Get the ‘first’ capture of the match

If there are no matches, this is the same as range, otherwise it’s capture(1)

Source

pub fn gmatch<'b, 'c>(&'c mut self, text: &'b str) -> GMatch<'a, 'b, 'c>

An iterator over all matches in a string.

The matches are returned as string slices; if there are no captures the full match is used, otherwise the first capture. That is, this example will also work with the pattern “(%S+)”.

let mut m = lua_patterns::LuaPattern::new("%S+");
let split: Vec<_> = m.gmatch("dog  cat leopard wolf").collect();
assert_eq!(split,&["dog","cat","leopard","wolf"]);
Examples found in repository?
examples/iter.rs (line 9)
3fn main() {
4    //~ let mut m = lp::LuaPattern::new("hello%");
5    //~ m.matches("hello");
6    //~ println!("ok");
7
8    let mut m = lp::LuaPattern::new("(%a+)");
9    let mut iter = m.gmatch("one two three");
10    assert_eq!(iter.next(), Some("one"));
11    assert_eq!(iter.next(), Some("two"));
12    assert_eq!(iter.next(), Some("three"));
13    assert_eq!(iter.next(), None);
14
15    let mut m = lp::LuaPattern::new("%S+");
16    let split: Vec<_> = m.gmatch("dog  cat leopard wolf").collect();
17    assert_eq!(split, &["dog", "cat", "leopard", "wolf"]);
18
19    let mut m = lp::LuaPattern::new("%s*(%S+)%s*=%s*(.-);");
20    let cc = m.captures(" hello= bonzo dog;");
21    assert_eq!(cc[0], " hello= bonzo dog;");
22    assert_eq!(cc[1], "hello");
23    assert_eq!(cc[2], "bonzo dog");
24
25    for cc in m.gmatch_captures("hello=bonzo dog; bye=cat;") {
26        println!("'{}'='{}'", cc.get(1), cc.get(2));
27    }
28
29    let mut m = lp::LuaPattern::new("%$(%S+)");
30    let res = m.gsub_with("hello $dolly you're so $fine", |cc| {
31        cc.get(1).to_uppercase()
32    });
33    assert_eq!(res, "hello DOLLY you're so FINE");
34
35    let mut m = lp::LuaPattern::new("(%S+)%s*=%s*([^;]+);");
36    let res = m.gsub_with("alpha=bonzo; beta=felix;", |cc| {
37        format!("{}:'{}',", cc.get(1), cc.get(2))
38    });
39    assert_eq!(res, "alpha:'bonzo', beta:'felix',");
40}
Source

pub fn gmatch_captures<'b, 'c>( &'c mut self, text: &'b str, ) -> GMatchCaptures<'a, 'b, 'c>

An iterator over all captures in a string.

The matches are returned as captures; this is a streaming iterator, so don’t try to collect the captures directly; extract the string slices using get.

let mut m = lua_patterns::LuaPattern::new("(%S)%S+");
let split: Vec<_> = m.gmatch_captures("dog  cat leopard wolf")
      .map(|cc| cc.get(1)).collect();
assert_eq!(split,&["d","c","l","w"]);
Examples found in repository?
examples/iter.rs (line 25)
3fn main() {
4    //~ let mut m = lp::LuaPattern::new("hello%");
5    //~ m.matches("hello");
6    //~ println!("ok");
7
8    let mut m = lp::LuaPattern::new("(%a+)");
9    let mut iter = m.gmatch("one two three");
10    assert_eq!(iter.next(), Some("one"));
11    assert_eq!(iter.next(), Some("two"));
12    assert_eq!(iter.next(), Some("three"));
13    assert_eq!(iter.next(), None);
14
15    let mut m = lp::LuaPattern::new("%S+");
16    let split: Vec<_> = m.gmatch("dog  cat leopard wolf").collect();
17    assert_eq!(split, &["dog", "cat", "leopard", "wolf"]);
18
19    let mut m = lp::LuaPattern::new("%s*(%S+)%s*=%s*(.-);");
20    let cc = m.captures(" hello= bonzo dog;");
21    assert_eq!(cc[0], " hello= bonzo dog;");
22    assert_eq!(cc[1], "hello");
23    assert_eq!(cc[2], "bonzo dog");
24
25    for cc in m.gmatch_captures("hello=bonzo dog; bye=cat;") {
26        println!("'{}'='{}'", cc.get(1), cc.get(2));
27    }
28
29    let mut m = lp::LuaPattern::new("%$(%S+)");
30    let res = m.gsub_with("hello $dolly you're so $fine", |cc| {
31        cc.get(1).to_uppercase()
32    });
33    assert_eq!(res, "hello DOLLY you're so FINE");
34
35    let mut m = lp::LuaPattern::new("(%S+)%s*=%s*([^;]+);");
36    let res = m.gsub_with("alpha=bonzo; beta=felix;", |cc| {
37        format!("{}:'{}',", cc.get(1), cc.get(2))
38    });
39    assert_eq!(res, "alpha:'bonzo', beta:'felix',");
40}
Source

pub fn gmatch_bytes<'b>(&'a mut self, bytes: &'b [u8]) -> GMatchBytes<'a, 'b>

An iterator over all matches in a slice of bytes.

let bytes = &[0xAA,0x01,0x01,0x03,0xBB,0x01,0x01,0x01];
let patt = &[0x01,b'+'];
let mut m = lua_patterns::LuaPattern::from_bytes(patt);
let mut iter = m.gmatch_bytes(bytes);
assert_eq!(iter.next().unwrap(), &[0x01,0x01]);
assert_eq!(iter.next().unwrap(), &[0x01,0x01,0x01]);
assert_eq!(iter.next(), None);
Examples found in repository?
examples/strings.rs (line 18)
11fn main() {
12    let file = env::args().skip(1).next().expect("provide a binary file");
13    let mut f = File::open(&file).expect("can't open file");
14    let mut buf = Vec::new();
15    f.read_to_end(&mut buf).expect("can't read file");
16
17    let mut words = LuaPattern::new("%a%a%a%a+");
18    for w in words.gmatch_bytes(&buf) {
19        println!("{}", str::from_utf8(w).unwrap());
20    }
21}
Source

pub fn gsub_with<F>(&mut self, text: &str, lookup: F) -> String
where F: Fn(Captures<'_, '_, '_>) -> String,

Globally substitute all matches with a replacement provided by a function of the captures.

let mut m = lua_patterns::LuaPattern::new("%$(%S+)");
let res = m.gsub_with("hello $dolly you're so $fine!",
    |cc| cc.get(1).to_uppercase()
);
assert_eq!(res, "hello DOLLY you're so FINE!");
Examples found in repository?
examples/iter.rs (lines 30-32)
3fn main() {
4    //~ let mut m = lp::LuaPattern::new("hello%");
5    //~ m.matches("hello");
6    //~ println!("ok");
7
8    let mut m = lp::LuaPattern::new("(%a+)");
9    let mut iter = m.gmatch("one two three");
10    assert_eq!(iter.next(), Some("one"));
11    assert_eq!(iter.next(), Some("two"));
12    assert_eq!(iter.next(), Some("three"));
13    assert_eq!(iter.next(), None);
14
15    let mut m = lp::LuaPattern::new("%S+");
16    let split: Vec<_> = m.gmatch("dog  cat leopard wolf").collect();
17    assert_eq!(split, &["dog", "cat", "leopard", "wolf"]);
18
19    let mut m = lp::LuaPattern::new("%s*(%S+)%s*=%s*(.-);");
20    let cc = m.captures(" hello= bonzo dog;");
21    assert_eq!(cc[0], " hello= bonzo dog;");
22    assert_eq!(cc[1], "hello");
23    assert_eq!(cc[2], "bonzo dog");
24
25    for cc in m.gmatch_captures("hello=bonzo dog; bye=cat;") {
26        println!("'{}'='{}'", cc.get(1), cc.get(2));
27    }
28
29    let mut m = lp::LuaPattern::new("%$(%S+)");
30    let res = m.gsub_with("hello $dolly you're so $fine", |cc| {
31        cc.get(1).to_uppercase()
32    });
33    assert_eq!(res, "hello DOLLY you're so FINE");
34
35    let mut m = lp::LuaPattern::new("(%S+)%s*=%s*([^;]+);");
36    let res = m.gsub_with("alpha=bonzo; beta=felix;", |cc| {
37        format!("{}:'{}',", cc.get(1), cc.get(2))
38    });
39    assert_eq!(res, "alpha:'bonzo', beta:'felix',");
40}
Source

pub fn gsub(&mut self, text: &str, repl: &str) -> String

Globally substitute all matches with a replacement string

This string may have capture references (“%0”,..). Use “%%” to represent “%”. Plain strings like “” work just fine ;)

let mut m = lua_patterns::LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
assert_eq!(res,"'2':a '3':b '4':c ");
Examples found in repository?
examples/range.rs (line 31)
4fn main() {
5    let mut m = LuaPattern::new("(%a+) one");
6    let text = " hello one two";
7    assert!(m.matches(text));
8    assert_eq!(m.capture(1), 1..6);
9    assert_eq!(m.capture(0), 1..10);
10
11    let v = m.captures(text);
12    assert_eq!(v, &["hello one", "hello"]);
13
14    let mut v = Vec::new();
15    assert!(m.capture_into(text, &mut v));
16    assert_eq!(v, &["hello one", "hello"]);
17
18    let bytes = &[0xFF, 0xEE, 0x0, 0xDE, 0x24, 0x24, 0xBE, 0x0, 0x0];
19
20    let patt = LuaPatternBuilder::new()
21        .bytes_as_hex("DE24")
22        .text("+")
23        .bytes(&[0xBE])
24        .build();
25
26    let mut m = LuaPattern::from_bytes(&patt);
27    assert!(m.matches_bytes(bytes));
28    assert_eq!(&bytes[m.capture(0)], &[0xDE, 0x24, 0x24, 0xBE]);
29
30    let mut m = LuaPattern::new("(%S+)%s*=%s*(%S+);%s*");
31    let res = m.gsub("a=2; b=3; c = 4;", "'%2':%1 ");
32    println!("{}", res);
33
34    let mut m = LuaPattern::new("%s+");
35    let res = m.gsub("hello dolly you're so fine", "");
36    println!("{}", res);
37}
Source

pub fn gsub_checked( &mut self, text: &str, repl: &str, ) -> Result<String, PatternError>

Globally substitute all matches with a replacement string

There will be an error if the result is bad UTF-8 (consider using gsub_bytes)

Source

pub fn gsub_bytes(&mut self, text: &[u8], repl: &[u8]) -> Vec<u8>

Globally substitute all byte matches with replacement bytes

Like gsub the replacement bytes may contain b“%0“ etc

let bytes = &[0xAA,0x01,0x02,0x03,0xBB];
let patt = &[0x01,0x02];
let mut m = lua_patterns::LuaPattern::from_bytes(patt);
let res = m.gsub_bytes(bytes,&[0xFF]);
assert_eq!(res, &[0xAA,0xFF,0x03,0xBB]);
Source

pub fn gsub_bytes_with<F>(&mut self, bytes: &[u8], lookup: F) -> Vec<u8>
where F: Fn(ByteCaptures<'_, '_>) -> Vec<u8>,

Globally substitute all byte matches with a replacement provided by a function of the captures.

let bytes = &[0xAA,0x01,0x02,0x03,0xBB];
let patt = &[0x01,0x02];
let mut m = lua_patterns::LuaPattern::from_bytes(patt);
let res = m.gsub_bytes_with(bytes,|cc| vec![0xFF]);
assert_eq!(res, &[0xAA,0xFF,0x03,0xBB]);

Auto Trait Implementations§

§

impl<'a> Freeze for LuaPattern<'a>

§

impl<'a> RefUnwindSafe for LuaPattern<'a>

§

impl<'a> Send for LuaPattern<'a>

§

impl<'a> Sync for LuaPattern<'a>

§

impl<'a> Unpin for LuaPattern<'a>

§

impl<'a> UnwindSafe for LuaPattern<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.