Search code examples
stringlualua-patterns

Dealing with speech marks with string.match


I have an xml page that I have a monitoring system scanning, here is the source data:

`<queues>
<queue name="workQueue">
<stats size="0" consumerCount="28" enqueueCount="29320" dequeueCount="37000"/>

And here is the code I have so far:

local pattern = " size=(%d+) "

local a = alarm.get("CO13974960-19518")

local vsize = string.match(a.message, pattern)

local sum = vsize

I'm trying to target this bit of data from the XML page:

stats size="0"

The value "0" is the number I am interested in, and I'm looking for a way to capture that figure (no matter what it reaches) via the script.

I think my script is looking for:

size=0 rather than size="0"

But I'm unsure on the correct syntax on how to do this.


Solution

  • In general, it's not a good idea to use Lua pattern (or regex) to parse XML, use a XML parser instead.


    Anyway, in this example,

    local pattern = " size=(%d+) "
    
    • Whitespace matters, so the white space in the beginning and end are trying to match white space character but failed.
    • You have already noticed that you need double quotes around (%d), they have to be escaped in double quoted strings.
    • + is greedy, it might work here, but the non-greedy - is a better choice.

    This works

    local pattern = "size=\"(%d-)\""
    

    Note you could use single quotes strings so that you don't need escape double quotes:

    local pattern = 'size="(%d-)"'