code / bp

Lines4.3K C3.3K Markdown541 YAML273 make110 Shell77 Lua54
(63 lines)
1 local bp = require 'bp'
3 local function repr(obj)
4 if type(obj) == 'table' then
5 local ret = {}
6 for k,v in pairs(obj) do table.insert(ret, ("%s=%s"):format(k, repr(v))) end
7 return ("{%s}"):format(table.concat(ret,","))
8 elseif type(obj) == 'string' then
9 return string.format("%q", obj)
10 else
11 return tostring(obj)
12 end
13 end
15 print("Matching:")
16 print(bp.match(".", "ABC"))
17 print(bp.match(".", "ABC", 2))
18 print(bp.match(".", "ABC", 3))
19 print(bp.match(".", "ABC", 4) or "no match")
20 print(bp.match(".", "ABC", 5) or "no match")
22 for m in bp.matches("(*`a-z) => '(@0)'", "one two three") do
23 print(repr(m))
24 end
26 print(("Replacing: %q (%d replacements)"):format(bp.replace("+`a-z", "(@0)", "one two three")))
29 print("Captures:")
30 local m = bp.match("@first=+`a-z _ @second=(+`a-z => 'XX@0XX') _ @+`a-z _ @last=+`a-z", "one two three four")
31 print(repr(m))
33 local m = bp.match("@dup=+`a-z _ @dup=+`a-z _ @two=(@a=+`a-z _ @b=+`a-z)", "one two three four")
34 print(repr(m))
37 print("Testing parse errors:")
38 local ok, msg = pcall(function()
39 bp.match(".;//;;; wtf", "xxx")
40 end)
41 if not ok then print(("Successfully got parse error: \"%s\"\n"):format(msg)) end
43 print("Testing builtins:")
44 print(bp.match("parens", "...(foo())..."))
47 print("Testing pat objects")
48 local pat = bp.compile("+`a-z")
49 print(pat)
50 print(pat:match("...foo..."))
51 print(pat:match("...baz..."))
52 print(pat:replace("{@0}", "...baz..."))
54 for m in pat:matches("hello world") do
55 print(m)
56 end
59 local ok, err = pcall(function()
60 bp.match("nonexistent", "xxx")
61 end)
62 assert(not ok)
63 print("(Successfully caught pattern matching error)")