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

Hi Monks

I am trying to split a string using regex.Here is the code i tried and the output that i get and the output i want.

#!/usr/bin/perl my $var='Aur S-P 250 Pre (Chlorine + cillin (cilli G caine) + Sulfate) +'; my @pos=split(/\s\(/,$var); for(@pos) { print "$_\n"; }

output i get

Aur S-P 250 Pre Chlorine + cillin cilli G caine) + Sulfate)

output i want

Aur S-P 250 Pre Chlorine + cillin (cilli G caine) + Sulfate

Replies are listed 'Best First'.
Re: regex splitting
by jethro (Monsignor) on Nov 19, 2009 at 22:15 UTC
    my @pos=split(/\s\(/,$var,2);

    Use 'perldoc -f split' to find out how that works

      Of course, that leaves the closing ')' in place :)

      Text::Balanced might be an option:

      $ perl -e " use strict; use Text::Balanced qw/extract_bracketed/; my $var='Aur S-P 250 Pre (Chlorine + cillin (cilli G caine) + Sulfate) +'; my ($ext,$rem,$pre)=extract_bracketed($var,'()',qr/[^(]+/); die 'oops' if $rem; $ext =~ s/(^\(|\)$)//sg; # remove lead/trail () print qq{$pre\n$ext\n}; " Aur S-P 250 Pre Chlorine + cillin (cilli G caine) + Sulfate
      Thanks a lot.What must I do to master regex??
        Mastering regex is a life-altering discipline. If you eat meat, you must become a vegetarian, and if you are a vegetarian, you must start eating meat.

        Or, you could just "RTFM"... perlretut (for beginners), and perlrequick (for the impatient), and perlre (The Whole Truth).

        When you need some diversion from all that, you can also browse the output of perldoc -q regex and perldoc -q regular -- some really choice bits there.

        There is a book with a very fitting title: "Mastering Regular Expressions" http://oreilly.com/catalog/9781565922570. But it doesn't seem to be aimed at beginners

        A better approach for you might be to read one of the essential perl books 'Learning Pearl' or 'Programming Perl', both from O'Reilly. The first one is a tutorial, with exercises, the second a reference work

        You also can find introductions on the net, for example on perlmonks (see Tutorials), or on http://perldoc.perl.org/ (essentially the man pages of perl with a nice web frontend)

Re: regex splitting
by colwellj (Monk) on Nov 19, 2009 at 22:34 UTC
    Its doing what you are asking it to. Which is split by space and left bracket. Split will keep doing that as many times as it can to make your array.
    You could look at adding a;
    join('\s\(',(@pos[1]..@pos[$#pos]))
    This is pretty ugly though.