[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: string.match(s, pattern, [init], WHY NOT [len])
- From: Dirk Laurie <dirk.laurie@...>
- Date: Thu, 12 Jul 2012 11:24:19 +0200
2012/7/12 Patrick Donnelly <email@example.com>:
> On Wed, Jul 11, 2012 at 7:39 PM, Nikolay Kostadinov <firstname.lastname@example.org> wrote:
>> This would make my life so much easier. Seriously why doesn't string.match
>> have a len argument? It's so useful.
> For more advanced pattern matching, use something like lpeg or a pcre
> binding. Lua pattern matching is not intended to solve all problems.
This answer is one that I know to be good for me too, yet I have been
putting off getting on top of lpeg for the simple reason that I don't
need it often enough that it will become part of me, as Lua and its
standard libraries have. I'll have to relearn it each time I use it.
So, let's return to the original question. Why is there not an optional
fourth parameter so that the spec would read
string.match(s, pattern, [init], [len])
The post is not clear to what `len` would apply — the original string
or the matched substring — but I assume the latter since the former is
really easy to implement. I.e. the OP wants this kind of behaviour:
string.match("x=1234;","=(%d+);",1,4) --> '1234'
string.match("x=1234;","=(%d+);",1,3) --> nil
Now, of course, "why not" questions are quite often simply answerable
by "because it has not even been considered", but in this case, I can
think of a quite substantial reason:
Because string.match can return several captures and there is not
much point in an extra argument that would only apply to one of them.
A second reason is:
Because the requested behaviour is so easy to achieve with existing
lmatch = function(str,pat,init,len)
for capture in str:sub(init,-1):gmatch(pat) do
if #capture<=len then return capture end
> return lmatch("x=1234;","=(%d+);",1,4)
> return lmatch("x=1234;","=(%d+);",1,3)