Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

perl string extract

by anu_1 (Acolyte)
on Oct 04, 2010 at 06:14 UTC ( #863260=perlquestion: print w/replies, xml ) Need Help??

anu_1 has asked for the wisdom of the Perl Monks concerning the following question:

I have to extract the filename
$line="logfile = filename , abcd=eflk , cxd"; $line=~/logfile\s*=\s*(.*?),/$1/; $file=$1;
But it will not work if the line is "logfile= filename", Is there any way for this particular case to specify there could be zero or one occurrence of comma. Thanks for your help

Replies are listed 'Best First'.
Re: perl string extract
by eyepopslikeamosquito (Bishop) on Oct 04, 2010 at 06:29 UTC

    Try making the comma optional?

    $line =~ /logfile\s*=\s*([^,]*),?/;

      Thanks a lot ..
Re: perl string extract
by ig (Vicar) on Oct 04, 2010 at 10:12 UTC

    If you don't want trailing spaces:

    $line =~ /logfile\s*=\s*([^,]*[^,\s])/;
Re: perl string extract
by Utilitarian (Vicar) on Oct 04, 2010 at 13:54 UTC
    Anchor your regex eg.
    $line=~ s/^ #Anchor at the beginning of the line logfile\s*=\s*([^,]*?) # As before (:?,.*)? # non-capturing optional block beginn +ing with a comma $ # Anchor at end of line /$1/x;

    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
Re: perl string extract
by prasadbabu (Prior) on Oct 04, 2010 at 06:28 UTC

    Please ignore this node.

    Something like this?

    use strict; use warnings; my $line = 'logfile = filename , abcd=eflk , cxd'; my $file; if ($line =~ /logfile\s*\=\s*(.+?)\s*\,?/){ $file=$1; } print "logfile=$file"; output: ======= logfile=filename
    Updated: Misunderstood the question. Added '?' after comma to make it optional.

    eyepopslikeamosquito++ Thanks.

    Prasad

      Your regex:

      if ($line =~ /logfile\s*\=\s*(.+?)\s*\,/){
      unilaterally matches a comma and so does not seem to match the OP's requirement to match with or without a comma.

      Even after your update:

      if ($line =~ /logfile\s*\=\s*(.+?)\s*\,?/){
      it still does not work correctly because the non-greedy (.+?) matches only the f in filename, so that $file has the value f when it should contain filename.
      I tried this solution but didn't work. The output is  logfile=f

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2022-05-20 17:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (75 votes). Check out past polls.

    Notices?