Search code examples
lualua-patterns

Problems understanding why certain Lua pattern fails


Consider the following tests completed on the lua cli:

Lua 5.2.4  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> line = "Conference 1-12345-a.b.c (1 member rate: 32000 flags: running|answered|enforce_min|dynamic|exit_sound|enter_sound)"

I'm trying to extract the 12345 from Conference 1-12345-a.b.c

This works:

> searchtextok = "1%-(%d%d%d%d)"
> print(string.match(line, searchtextok));
1234

But this fails:

> searchtextok = "1%-(%d%d%d%d)%-"
> print(string.match(line, searchtextok));
nil

But I don't understand why. I'm currently reading this but if you have any pointers, that'd be great.


Solution

  • What your first pattern means is "1, followed by dash, followed by 4 digits". The second one is the same, but followed by a dash. Since after the four digits you have another digit (1-12345-a.b.c) and not a dash, the match fails.


    You probably wanted to match 5, not 4 digits. Just change it to:

    "1%-(%d%d%d%d%d)%-"