Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 275
greenage Avatar asked Mar 31 '16 11:03

greenage


People also ask

How do you escape quotation marks in a string?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.

How do you use quotation marks in a string?

Within a character string, to represent a single quotation mark or apostrophe, use two single quotation marks. (In other words, a single quotation mark is the escape character for a single quotation mark.) A double quotation mark does not need an escape character.

Do strings require quotation marks?

Strings in JavaScript are contained within a pair of either single quotation marks '' or double quotation marks "". Both quotes represent Strings but be sure to choose one and STICK WITH IT. If you start with a single quote, you need to end with a single quote.

What is the function of double quotation marks when using a string?

Quotation marks are used to specify a literal string. You can enclose a string in single quotation marks ( ' ) or double quotation marks ( " ). Quotation marks are also used to create a here-string. A here-string is a single-quoted or double-quoted string in which quotation marks are interpreted literally.


Video Answer


1 Answers

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-)"'
like image 82
Yu Hao Avatar answered Sep 29 '22 16:09

Yu Hao