in reply to reg exp to find presence of value in a list of comma seperated list
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!
|
|---|