Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] regexp

Expand Messages
  • Andrew Johnson
    [regarding extracting data from between [ and ] delimiters] ! oh, don t forget to escape the [ and ]... sorry about that. ! ! $yourlinevariable =~
    Message 1 of 3 , Jul 12, 2000
    • 0 Attachment
      [regarding extracting data from between [ and ] delimiters]

      ! oh, don't forget to escape the [ and ]... sorry about that.
      ! $yourlinevariable =~ /\[(.+)\]/;
      ! $result = $1;
      ! print("your result is $result\n");

      Andy Dougherty's reply pointed out the possible complexities of
      this seemingly simple problem, and gave pointers to potential
      solutions (modules) that will help.

      However, I thought I'd point out that, aside from not taking those
      complexities into account, the above code snippet uses the $1
      variable without first checking that the match succeeded -- if the
      match failed, $1 could contain the result of a previous match, or be
      undefined. For example, if, while reading each line, the program
      first extracts a data number from the beginning of the string you
      could have this kind of thing happen if you aren't careful:

      $_ = '123: foo bar quux';
      print "Data number = $1\n";

      print "result = $1\n"; # oops

      It is a good idea to conditionalize code that uses match variables:

      print "result = $1\n";

      Or, if finding multiple, non-nested, non-overlapping, balanced pairs
      on a line, loop through the matches:

      foreach my $result (/\[([^\]]+)\]/g){
      print "$result\n";

      This was just a tip -- in the case of the problem at hand I'd second
      Andy's suggestion of checking out CPAN for modules that deal with
      delimited data.


      Andrew L. Johnson http://members.home.net/andrew-johnson/
      Some people, when confronted with a problem, think 'I know,
      I'll use regular expressions.' Now they have two problems.
      -- Jamie Zawinski, on comp.lang.emacs
    Your message has been successfully submitted and would be delivered to recipients shortly.