lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Another way that works for the 5 samples but still needs 2 matches:

> p1 = "%a*%;(%d+)"
> p2 = "^%a*$" 
> s1 = "foo"
> s2 = "foo;1"
> s3 = "foo;444"
> s4 = "foo;"
> s5 = "foo23"
> s = s1
> s:match(p1) or s:match(p2)
foo
> s = s2
> s:match(p1) or s:match(p2)
1
> s = s3
> s:match(p1) or s:match(p2)
444
> s = s4
> s:match(p1) or s:match(p2)
nil
> s = s5

On Mon, Sep 9, 2019 at 8:22 PM Sean Conner <sean@conman.org> wrote:

  Normally I reach for LPEG to handle my parsing chores, but I have a
project where that ... well, I'd be reimplementing a form of regex anyway,
so why not use Lua patterns and avoid that mess.

  But I have an issue that I do not know the answer to---I suspect there
isn't an answer but "use a real regex or LPEG".  But I thought I would ask
anyway.

  I have a pattern that looks like this BNF:

        TEXT    = 'A' - 'Z' / 'a' - 'z'
        DIGIT   = '0' - '9'

        pattern = 1*TEXT [ ';' 1*DIGIT ]

  In English, text, optionally followed by a semicolon and some digits.  So
some valid examples:

        foo
        foo;1
        foo;444

  Invalid examples are

        foo;
        foo23

  If there's a semicolon, it must be followed by a digit; if there's no
semicolon, no digits.  This is trivial (to me) in LPEG.  No so with Lua
patterns.  There's:

        "%a%;?(%d+)

but that allows "foo23" to slip through.  What I would like would be:

        %a(%;(%d+))?

although that doesn't work, since the '?' can (if I'm reading the
documentation right) only follow a character class, not a grouping.

  Am I missing something?

  -spc (I mean, besides "using LPEG"?)