FW: [Kc] Puzzle: 100 Monkeys

Gene Dascher gedascher at multiservice.com
Wed Jan 15 11:39:48 CST 2003


Forwarded at the request of Garrett.  I'm showing my ignorance so you don't
have to show yours!!!

Gene

-----Original Message-----
From: Garrett Goebel [mailto:garrett at scriptpro.com]
Sent: Wednesday, January 15, 2003 11:33 AM
To: 'Gene Dascher'
Subject: RE: [Kc] Puzzle: 100 Monkeys


Gene,
The regular expression used to verify the answer submission's format is
probably an issue for a number of kc.pm members. Would mind my reposting the
following explanation to the list?
Gene Dascher wrote:
>
> Is that regex right?  What is the ? supposed to be matching?
>
> m/^\d+(?:\s\d+)*$/
(?:pattern) means cluster but don't capture... It groups expressions but
doesn't capture their values to the magic $1, $2, ... $n variables. It is
faster and more efficient than the functionally equivalent m/^\d+(\s\d+)*$/,
because it doesn't have to copy the values matched in (\s\d+) into $1.
To illustrate, try:
print '1 2 3' =~ m/^\d(?:\s\d+)*$/;
print '1 2 3' =~ m/^\d(\s\d+)*$/;
m// in list context returns a list consisting of the subexpressions matched
by the capturing parentheses in the pattern, i.e., ($1, $2, $3...). When
there are no capturing parentheses in the pattern, the return value is the
list (1) for success. With or without parentheses, an empty list is returned
upon failure.
In our example, print takes a list of arguments, and thus supplies a list
context for the return value of m//. Just to round out the explanation, in
scalar context, each execution of m//g finds the next match, returning true
if it matches, and false if there is no further match.
So the first example would print:
1
Whereas the second would result in:
 3
Both would pass the test for truth, but the example using non-capturing
parens is slightly more efficient.


> Please correct me, but it makes more sense like this:
> m/^\d+(\:\s\d+)*$/
> or
> m/^\d+(:?\s\d+)*$/
neither
m/^\d+(?:\s\d+)*$/ would match the string "1 2 3".
Your alternatives:
  m/^\d+(\:\s\d+)*$/ would match "1: 2: 3"
  m/^\d+(:?\s\d+)*$/ would match both "1 2 3" and "1: 2: 3"
The second would match both. '?' is one of the standard regex quantifiers: +
* ?. So :? would match either 0 or 1 occurances of ':'.
--
Garrett Goebel
IS Development Specialist
ScriptPro                   Direct: 913.403.5261
5828 Reeds Road               Main: 913.384.1008
Mission, KS 66202              Fax: 913.384.2180
www.scriptpro.com          garrett at scriptpro.com




More information about the kc mailing list