lua-users home
lua-l archive

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


2017-03-30 14:43 GMT+02:00 John Logsdon <j.logsdon@quantex-research.com>:
> Folks
>
> I have a regex problem in 5.2.4 either under Cygwin or Ubuntu 16.04.
>
> I want to match two character strings like Aa, AA, A2 where the first
> letter is a capital and the second could also be a digit using
> string.gmatch to generate an iterator.
>
> If I check with string.match this works:
>
> print(string.match("blah blah Aa boo ","%u%w"))
> print(string.match("blah blah AA boo ","%u%w"))
> print(string.match("blah blah A3 boo ","%u%w"))
>
> But if I use gmatch as in a simple function:
>
> local str=" A1 blah AA boo Ax "
>
> local function getCase(A,str)
>   local nextCase = string.gmatch(str,"%u%w")
>   local N=nextCase()
>   while N ~=  nil do
>     if type(Q[N]) == 'table' then A[N] = #Q[N] end
>     N=nextCase()
>   end
>   return A
> end
>
> The function takes a table and checks whether Q[A3] for example exists and
> is a table, if so, returning the length of the table in A.

Assuming that Q is an upvalue or a global table, of course.

It works for me:

> str=" A1 blah AA boo Ax "
> Q={}
> Q.A1={1}
> Q.AA={1,2}
> Q.Ax={1,2,3}
> A={}
> getCase(A,str)
table: 0x2493710
> for k,v in pairs(A) do print(k,v) end
AA    2
A1    1
Ax    3

BTW You could code the function more compactly:

function getCase(A,str)
  local nextCase = string.gmatch(str,"%u%w")
  for N in nextCase do
    if type(Q[N]) == 'table' then A[N] = #Q[N] end
  end
  return A
end