• Subject: Re: Finding intermediate token in a string
• From: Austin Einter <austin.einter@...>
• Date: Mon, 7 Jul 2014 15:11:17 +0530

Hi Sean Conner

Many thanks for detail explanation and proper code.

Finally I need to go for LPeg approach. Now I am just about to prove that with Lua, I will be able to simulate a sip call flow.

Thanks

Austin

On Mon, Jul 7, 2014 at 1:36 PM, Sean Conner wrote:
It was thus said that the Great Austin Einter once stated:
> Hi All
> I can have an input string with any one of below formats
>
> \r\nContent-Length: 100 \r\n
> \r\nContent-Length    :      100 \r\n
> \r\nContent-Length:100    \r\n
>
> Input string can be of any one value from above examples
>
> My aim is to extract 100 as an integer.
>
> What is the best way to do it.

In my opinion, use LPeg for parsing.  Yes, there is some learning curve,
but for what you are trying to do, there isn't anything better than LPeg.  I
use it at work all the time for parsing issues.

Here's an example that applies to your case:

local lpeg = require "lpeg"

local P  = lpeg.P
local S  = lpeg.S
local C  = lpeg.C

local crlf    = P"\r"^-1 * P"\n"
local lwsp    = S" \t"
local eoh     = (crlf * #crlf) + (crlf - (crlf^-1 * lwsp))
local lws     = (crlf^-1 * lwsp)^0
local value   = (P(1) - eoh)^0
/ function(v)
return v:gsub("[%s%c]+"," ")
end
local name    = C((P(1) - (P":" + crlf + lwsp))^1)
local header  = name * lws * ":" * lws * value * eoh

hdr,val = header:match "Content-Length: 100 \r\n"               print(hdr,val)
hdr,val = header:match "Content-Length    :      100 \r\n"      print(hdr,val)
hdr,val = header:match "Content-Length:100    \r\n"             print(hdr,val)