Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: reg exp to find presence of value in a list of comma seperated list

by kennethk (Abbot)
on Nov 17, 2009 at 20:42 UTC ( [id://807790]=note: print w/replies, xml ) Need Help??


in reply to reg exp to find presence of value in a list of comma seperated list

I suspect that for whatever you are doing, you would be better off splitting first or better yet using a CSV module (like Text::CSV), but it's fairly trivial to check with:

/(?:^|,)value1(?:,|$)/

where I've used non-capturing groups with alternators to make it insensitive to whether it is next to commas or the start/end of the list. See perlretut.

Replies are listed 'Best First'.
Re^2: reg exp to find presence of value in a list of comma seperated list
by kgforperl (Novice) on Nov 17, 2009 at 21:11 UTC
    Thank you kennethk. I am learning perl now. I found that this one also is working $commalist =~ /,$item,/. I know there might be more than one way to do this, but if you don't mind can you tell me the difference between the one you suggested and this one

      First, welcome to the Perl community. I hope you get as much enjoyment out of working with Perl as I have.

      Your regular expression misses the case where either the first or last element of your list is the element you wish to check for. Consider:

      #!/usr/bin/perl use strict; use warnings; my $csv = 'value1,value2,value3'; my $value = 'value1'; if ($csv =~ /(?:^|,)$value(?:,|$)/) { print "Yes\n"; } else { print "No\n"; } if ($csv =~ /[,]$value[,]/) { print "Yes\n"; } else { print "No\n"; }

      Mine catches those cases since the first group ((?: ... )) matches on either the start of the string (^) or a comma and the second group matches on either the end of the string ($) or a comma. Since value1 is not surrounded by commas, yours will not find it. Note that both cases will fail if there is white space in the csv that is not in the $value.

      You might also note there is no need to define the single-element character class [,] as opposed to just using the raw comma ,.

      As a side note, please read Markup in the Monastery, since by not wrapping your code in code tags, you inadvertently converted [,] into a link - when this happens, monks frequently misread your intention.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://807790]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2024-03-28 10:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found