Here is another solution below.

You didn't mention whether spaces are allowed in the comma separated fields or not or for that matter embedded commas within some quoted thing in the comma separated fields.

Here I allow spaces around the values assuming that the values are single tokens and do not contain spaces. This uses split to create a list of tokens (without commas or spaces) and the the scalar value of grep{} is used to count the number of times that value1 is seen. value1 must not have any characters before or after it. That is what the "carrot" and "dollar sign" do. Otherwise something like value1value2, value3 would match.

The regex stuff is a bit easier here, but it runs slower. If you have some comma separated thing that can come from a spreadsheet or whatever, you should consider one of the parser modules for CSV files. Search on CSV and you will find several.

#!usr/bin/perl -w use strict; my $line = "value3,value7, value1 ,value5"; #to show what the split does... print split(/[, ]/,$line),"\n"; if (grep {/^value1$/} split(/[, ]/,$line) ) { print "value1 found!\n"; } #prints: #value3value7value1value5 #value1 found!

In reply to Re: reg exp to find presence of value in a list of comma seperated list by Marshall
in thread reg exp to find presence of value in a list of comma seperated list by kgforperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.