lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 01/03/2015 14:04, Pablo Botelho wrote:
Hello everyone,
     my knowledge about regular expressions is very limited, so I'm struggling with this
problem:

Given 2 strings

s1 = '/foo/:bar/oof/:rab'

s2 = '/foo/lua/oof/rocks'

I would like to produce the following information

1) If they match (these two above should match)

2) a table holding the values of 's2' in with the corresponding name in 's1'
In this case we would have: { bar = "lua", rab = "rocks" }

I think this algorithm solves it, but I cant figure how to implement it:

a) store the placeholders ':' indexes as KEYS of a table, and the respective VALUES being
the name of these placeholders

  example with s1:
local aux1 = { "6" = "bar", "15" = "rab" }

b) with the keys of 'aux1' fetched as indexes, extract the values of 's2'
into another table
local aux2 = {"6" = "lua", "15" = "rocks}

c) finally merge them two into one table (this one is easy :P)
{ bar = "lua", rab = "rocks" }

Hello

Your specification leaves some things implicit, so are subject to interpretation / different implementations.

For example, will the placeholders always be in a path-like string? Will they always end with a slash? I am not sure why your proposed implementation uses indexes. If placeholders always uses a full entry between slashes, I would rather index them by the number of entries (or slashes) before them. As pointed out, it would better account for length differences between placeholders and strings they must match. And, indeed, a split() function would do the job nicely, without having to rely (much) on regular expressions.

HTH, regards.

--
Philippe Lhoste
--  (near) Paris -- France
--  http://Phi.Lho.free.fr
--  --  --  --  --  --  --  --  --  --  --  --  --  --