Wildcards in regexp

Posted by Kora on Mon 12 Mar 2012 04:55 AM — 2 posts, 11,737 views.

#0
I'm writing a script which I would like to respond to 'random *'. I would also like 'rando *' or 'rand *' to fire the script, but not 'randm *'. It's important the alias can take and recognize a parameter, so I need to be able to put a wildcard after whatever I do.

"^rand(om?)?$" gives me what I want, but
"^rand(om?)? (.*)$" gives me the following error:

Quote:
Run-time error
Plugin: Random (called from world: Inferno)
Function/Sub: GenerateNumber called by alias
Reason: processing alias "RandomParameter"
[string "Plugin"]:3: bad argument #2 to 'random' (number expected, got nil)
stack traceback:
[C]: in function 'random'
[string "Plugin"]:3: in function <[string "Plugin"]:1>
Error context in script:
1 : function GenerateNumber(name, line, wildcards)
2 : n = tonumber(wildcards[1])
3*: Note("Random number [0-" .. wildcards[1] .. "]: " .. math.random(0, n))
4 : end -- function

Clearly, it's having trouble picking up the wildcard now. This makes no sense.

To clarify, "^random (.*)$" without the quantification gives me no error. Neither does "^rando?m? (.*)$" but that will match 'randm *'.

Does anyone know what's wrong?

EDIT: Okay, so I thought about it and decided to try picking up wildcards[2] instead and that's fixed my problem. However, I'm still confused as to why. Does it just take anything in parentheses and add it to the wildcards array? And if so, why is wildcards[1] nil and not "om"?
Amended on Mon 12 Mar 2012 05:52 AM by Kora
Australia Forum Administrator #1
Things in paranthese are "captures" and end up in the wildcards array. Unless, that is you turn it off, like this:




^rand(?:om?)? (.*)$


The ?: says "don't capture this group".

What might be better is to name the desired wildcard and then it doesn't matter what number it is, eg.


^rand(om?)? (?P<rand>.*)$


Now your code can say:


n = tonumber(wildcards.rand)


That pulls in the wildcard named "rand".