Ryan Moszynski wrote:
>
> I need to write some code to allow users to specify which of a whole
> bunch of elements(e.g.512/1024) that they want to view.  My idea for
> how to do this was to have them input a semicolon delimited list, for
> example:
>
> 1-10;25;33;100-250
>
>
> i tried using this to check to make sure they input a valid list that
> i can process:
> ###########
>        foreach ($temp2 = <>) {
>
>     $list1 = $temp2;
>
>     if ($list1 =~ /(\s*\d+;)+/g || $list1 =~ /(\s*\d+;)+/g ) {
>
>         print "yay\n";
>     }else {print "boo\n";};
>
>     #print "...",$list1, "...\n";
>
>    }
> ###########
>
> which doesn't work, because as soon as it matches the first time,
> anything goes.  How do i get it check for repetition, even though i
> don't know how many repetitions there will be.  there could be
> 1,2,3,5, even 10 groupings.
>
> so the pattern isns't hard, there has to be a number, then either a
> '-' or s ';', then repeat or not.  the only special case is the first
> one which could just be a single number, or a number '-'number.  I
> just don't know how to implement it.
>
> (#(-||;))(#(-||;))(#(-||;))

Hi Ryan

Stuff like this is easier if you build regex expressions to match individual
elements of the pattern and then use those to build up the expression for the
whole string. each item separated by teh semicolons is a string of digits,
optionally followed by a hyphen and another string of digits. So we ccan write
this:

  my $element = qr/\d+(-\d+)?/;

and the whole string must match any number of such elements followed by a
semicolon, ending with an element on its own:

  my $pattern = qr/^($element;)*$element$/;

so we can write the whole program:

  use strict;
  use warnings;

  my $string = '1-10;25;33;100-250';

  my $element = qr/\d+(-\d+)?/;
  my $pattern = qr/^($element;)*$element$/;

  if ($string =~ $pattern) {
    print "OK\n";
  }
  else {
    print "NOT OK\n";
  }

HTH,

Rob

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to