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

I have a variable $CD which can have one or more of C, E, T, L, M, N, P or A. and can be a comma delimeted list if more than one is specified.

ex: $CD ="C,M,N";
or
$CD ="P"; etc.

How can i do with regular expression? Please tell me the regular expression to check above.
  • Comment on Regular expression for combination of data

Replies are listed 'Best First'.
Re: Regular expression for combination of data
by wind (Priest) on Jul 31, 2007 at 07:06 UTC
    The following should validate what you specified:
    while (<DATA>) { if (/^[CETLMNPA](?:,[CETLMNPA])*$/) { print "Validated: $_"; } else { print "Incorrect: $_"; } } __DATA__ C,M,N C,MN C,,M,N P T Z E,M,N,P,A,A
    - Miller

    PS: It would be great if you spell checked your node title :)
Re: Regular expression for combination of data
by moritz (Cardinal) on Jul 31, 2007 at 08:04 UTC
    If you want to make a list from your string, use split:

    my @list = split m/,/, $CD;

    Then your processing might be easier...

Re: Regular expression for combination of data
by 0x000 (Acolyte) on Jul 31, 2007 at 06:58 UTC
    if $CD =~ /[CETLMNPA,]+/ { print "it matched\n"; }
    You need to be more specific with what you're trying to do.
      This is not working. When $CD ="CM" (which is invalid) It says it matched. The letters must be seperated by comma (,)
      valid values are: "C,M" "C" "C,P"
      invalid values are : "CM", "PC" (each letter must be seperated by comma(,))
Re: Regular expression for combination of data
by radiantmatrix (Parson) on Jul 31, 2007 at 15:06 UTC

    I'm not sure from your question what exactly you're trying to accomplish. Here are a couple of options...

    1. Determine if the value in $CD is valid
      my $valid_chars = 'CETLMNPA'; if ($CD =~ m/^[$valid_chars](?:,[$valid_chars])*$/) { print "Valid!" } else { die "Invalid!" }

      Let's break down that regular expression:

      m/ ^[$valid_chars] #the string must start with one of the valid char +s (?: #start group, but don't capture! , #could have a comma [$valid_chars] #and another valid char )* #and that comma+valid char could repeat 0 or more + times $ #until the end of the string /x #this is here to allow me to use all these commen +ts
    2. Use as configuration values

      For example, if I want to know at various points in code if a given flag is set:

      my %config = map { $_ => 1 } split(',', $CD); ## later on... if ( $config{L} ) { print "L was set!" }

      You might use the validation from above in combination with this.

    <radiant.matrix>
    Ramblings and references
    The Code that can be seen is not the true Code
    I haven't found a problem yet that can't be solved by a well-placed trebuchet