On Mar 7, 2014, at 10:05 PM, Bill McCormick <wpmccorm...@gmail.com> wrote:

> I have the following string I want to extract from:
> 
> my $str = "foo (3 bar): baz";
> 
> and I want to to extract to end up with
> 
> $p1 = "foo";
> $p2 = 3;
> $p3 = "baz";
> 
> the complication is that the \s(\d\s.+) is optional, so in then $p2 may not 
> be set.
> 
> getting close was
> 
> my ($p1, $p3) = $str =~ /^(.+):\s(.*)$/;


You can make a substring optional by following it with the ? quantifier. If you 
substring is more than one character, you can group it with capturing 
parentheses or a non-capturing grouping construct (?: ).

Here is a sample, using the extended regular expression syntax with the x 
option:

my( $p1, $p2, $p3 ) = $str =~ m{ \A (\w+) \s+ (?: \( (\d+) \s+ \w+ \) )? : \s 
(\w+) }x;
if( $p1 && $p3 ) {
        print “p1=$p1, p2=$p2, p3=$p3\n”;
}else{
        print “No match\n”;
}

Always test the returned values to see if the match succeeded.

So if '(3 bar)’ is not present, does the colon still remain? That will 
determine if the colon should be inside or outside the optional substring part.


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to