[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Capture patterns
- From: "Eric Tetz" <erictetz@...>
- Date: Tue, 8 Jan 2008 09:24:23 -0800
On Jan 8, 2008 7:04 AM, Jeff Wise <jwise@sealyrealty.com> wrote:
> Look at all these possible formats:
>
> 1. $100.00
> 2. .00
> 3. 100,000.00
> 4. -1,234.56
> 5. (1,234.56)
> 6. 1,234.56CR
> 7. 1,234.56-
> 8. +100.00
If you strip out the superfluous characters:
input = string.gsub(input, "[$,%+%s]", "")
It reduces the number of formats to 6.
One approach is just to try every valid pattern until one sticks:
-- I have no idea what 'CR' appended to a number means,
-- so I'll pretend it means negative...
function match_number(s)
s = s:gsub("[$,+%s]", "") -- strip garbage
local n =
s:match("%-(%d+%.%d+)") -- -22.22
or s:match("(%d+%.%d+)%-") -- 22.22-
or s:match("%((%d+%.%d+)%)") -- (22.22)
or s:match("(%d+%.%d+)CR") -- 22.22CR
return n and -n
or s:match("(%d+%.%d+)") -- 22.22
or s:match("(%.%d+)") -- .22
end
Or you could use one pattern and test if you caught any of the extra stuff:
function match_number(s)
s = s:gsub("[$,+%s]", "") -- strip garbage
local pre, n, post = s:match("([-(]?)(%d*%.%d+)([CR-]?)")
return (pre ~= "" or post ~= "") and -n or n
end
I'm sure there are a dozen other ways to skin this cat, but I've gotta
get to work...
> I think that the section could be better
> organized by covering the "magic characters" in
> order instead of randomly. This would make the
> text more useful as a reference
Check out the online manual. It has exactly what you want. :)
Cheers,
Eric