lua-users home
lua-l archive

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


Henryla wrote:
> I would use a table for breaking down the phone number
> 
> phoneTable = {
> 1 = "<regular expression for country code 1>",
> 852 = "<regula expression for country code 852>"
> }

This seems fine for a few entries, but maintaining this by hand
for a scheme that deals with all country prefix codes (if there is
such a requirement) will be a killer. Better to load and build
phoneTable automatically, either from a separate file or from a
long string section.

> phoneNumber = "<phone number>"
> for k,v in pairs(phoneTable) do
>   s,e = string.find(phoneNumber,"^" .. tostring(k))
>   if s then
>     s,e,phones = string.find(phoneNumber,v)
>     < do any process you want >
>   end
> end

For every phone number, the above needs to iterate and run at
least one regex. A string.sub, followed by a table lookup or two
is probably faster. Since Lua provides a hash table type by
default, cooking up a lookup algorithm is intuitive and would
probably be better than a brute force iterative algorithm.

But it isn't really necessary to do any further processing after
you split out the country code. North American codes are special,
because they got cute and put some countries in their 1-XXX form.
So at most, perhaps we want to validate the 1-XXX and find out the
US state of the number. The rest of the digits cannot be split
between the classical area code and local number, because I doubt
if it is practical to tackle that. All the regexes are overkill.
However, if users are entering spaces and punctuation also,
smarter pattern matching is probably wise.

It is sometimes not absolutely necessary to use regexes, if one
can write an algorithm in a clear and expressive manner without
using regexes. In this case, a well-written algorithm using
string.sub and a table lookup or two wouldn't be very hard to grok
and may be just as easy to understand and maintain.

-- 
Cheers,
Kein-Hong Man (esq.)
Kuala Lumpur, Malaysia