lua-users home
lua-l archive

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


On 8 June 2011 08:46, Igor Medeiros <igorosbergster@gmail.com> wrote:
> Excuse me if the question does not belong to this thread, but I'm not used
> to the lua patterns. I'm more used to define patterns using regex
>
> I have one more doubt. How do i define a lua pattern that corresponds to
> following regular expression?
>
> (systemScreen([1 .. 9])|systemAudio([1 .. 9]))
>
> that is, the text must be of type:
>
> systemScreen(1) or systemScreen(2) or ... or .. systemScreen(9) or
> systemAudio(1) or systemAudio(2) or ... or .. systemAudio(9)
>
> thanks
> Igor
>
>
>
> 2011/6/1 Igor Medeiros <igorosbergster@gmail.com>
>>
>> Thanks a lot
>>
>> Regards
>> Igor
>>
>>
>> 2011/6/1 Dirk Laurie <dpl@sun.ac.za>
>>>
>>> >
>>> > How to represent the pattern ([a-z]|[A-Z]|_)+([a-z]|[A-Z]|[0-9]_)* in
>>> > Lua's format pattern.
>>> >
>>> > I tried
>>> >
>>> > patt = '([a-z]|[A-Z]|_)+([a-z]|[A-Z]|[0-9]_)*'
>>> >
>>> > string.match( '_id', patt )
>>> >
>>>
>>> patt = "[%a_][%w_]*"
>>> print (string.match("_id",patt))    --> _id
>>> print (string.match("A_1.",patt))   --> A_1
>>>
>>> I find Lua's patterns much more intuitive than variations of regex.
>>>
>>> Dirk
>>>
>>
>
>

The following would work:

local capture = string.match(s, "system[SA][cu][rd][ei][eo]n?%([1-9]%)")

... but it’s a bit cumbersome, and you have to be sure your input will
conform and won't be something like systemSaudio(7)

A more Lua way of doing this might be (if the input isn't embedded
within longer strings):

local t = {}
for i = 1, 9 do
    t["systemScreen(" .. i .. ")"] = true -- or a function you want to call
    t["systemAudio(" .. i .. ")"] = true
end

if t[s] then print("match!") end -- or if t[s] then t[s](s) end

Otherwise, Lpeg is your friend...

Vaughan