Search code examples
luastring-matchinglua-patterns

Capture group in Lua pattern matches literal digit character instead of capture group


I want to extract the VALUE of lines containing key="VALUE", and I am trying to use a simple Lua pattern to solve this.

It works for lines except for those which contains a literal 1 in the VALUE. It seems the pattern parser is confusing my capture group for an escape sequence.

> return  string.find('... key = "PHONE2" ...', 'key%s*=%s*(["\'])([^%1]-)%1')
5       18      "       PHONE2
> return  string.find('... key = "PHONE1" ...', 'key%s*=%s*(["\'])([^%1]-)%1')
nil
>

Solution

  • You do not need to use the [^%1] at all. Just use .- as it, by definition, matches the smallest possible string.

    Also, you can use multiline string syntax, to not have to escape the quotes in your pattern:

    > s=[[... key = "PHONE1" ...]]
    > return s:find [[key%s*=%s*(["'])(.-)%1]]
    5       18      "       PHONE1
    

    The pattern [^%1] actually means, do not search for characters % and 1 individually.