Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: capture optional text

by haukex (Archbishop)
on May 18, 2017 at 04:56 UTC ( [id://1190514]=note: print w/replies, xml ) Need Help??


in reply to capture optional text

TIMTOWTDI, personally I like to be explicit and use non-capturing groups for this kind of thing, like (?: ... )? and/or (?: ... | ... ) (although the former gets a little less readable in the example below). The following regex requires there to be a space before the comment, and I've also used the /x modifier to make it a bit more readable.

while (<DATA>) { my ($host,$comment) = m{^ \s* (\w+) (?: \s+ \#+ (.*) | \s* ) $}x #OR: # m{^ \s* (\w+) (?: \s+ (?: \#+ (.*) )? )? $}x or die "failed to parse '$_'"; $hosts{$host} = $comment//''; }

Update: Yet another option: m{^ \s* (\w+) \s+ (?: \#+ (.*) )? $}x - this works because even if there's nothing following the \w+, the \s+ will match the newline, and $ matches either at the end of the string or at the newline at the end of the string.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1190514]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2024-04-16 11:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found