[Brisbane-pm] Still Struggling With Regex Syntax

Jacinta Richardson jarich at perltraining.com.au
Sun Apr 15 21:54:40 PDT 2007


Martin Jacobs wrote:

> $rain = ($rain =~ m|\d+\.?\d*|);
> 
> It returns 1, which, presumably, is the number of times it gets a match.


Almost there:

($rain) = ($rain =~ m|
		(          # start capturing
		 \d+       # some digits, 1 or more
		 (:?       # open grouping braces (non-capturing)
		    \.     # a dot
		    \d+    # one or more digits
		 )?        # close grouping: make optional
		)          # stop capturing
	|x
);

Just like when you're capturing for $1 you need to use parentheses inside your
regular expression.  A regular expression returns the number of matches made in
scalar context, and the match results in list context.  Thus to get the actual
match, you need to capture into a list.  So you need the parentheses on the
outside as well.

If you want to allow numbers like: "13."  then change the second \d+ to \d*  If
you want to insist that rain _only_ contain this match (so that you can reject
invalid lines), then anchor the expression to the start and end:

($rain) = ($rain =~ m|
                ^          # start of string
		(          # start capturing
		 \d+       # some digits, 1 or more
		 (:?       # open grouping braces (non-capturing)
		    \.     # a dot
		    \d+    # one or more digits
		 )?        # close grouping: make optional
		)          # stop capturing
                \s*$       # optional whitespace, followed by end of string
	|x
);

It's the "x" at the end, which is allowing me to add comments and arbitary
whitespace.

All the best,

	Jacinta

-- 
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |


More information about the Brisbane-pm mailing list