Rob Dixon wrote: > > Scott E Robinson wrote: > > > > I don't exactly want to ask this now, since I just spent much of the > > evening trying to handle this case, but I wonder if there's an easy > > way to > > keep the following regular expression from matching if the string in > > the > > regex is null: > > > > $_ = ":B000:L520:M260:M:88:8:M602:"; > > $string_to_match="whatever"; > > $count = () = /\b($string_to_match)\b/g; > > > > If $string_to_match is null, whatever's in $_ matches it -- and for > > some > > reason i don't understand it matches twice for every colon-delimited > > piece > > of $_, though that hardly matters. > > > > Is there an easy way to keep the null string from matching anything? > > It would have saved me an evening if I'd known about it. > > Hi Scott. Sorry about your wasted evening. As Steve says the > problem is that the \b (word-boundary) assertion is zero-width. > This means that further contents of the regex can match in the > same place in the string. Once your variable contents have been > expanded, the regex becomes /\b()\b/g so both \bs simply match > at the same place. > > You can test your $string_to_match before applying the regex or, > in your particular case, you could check that string is surrounded > by non-word characters > > $_ = ":B000:L520:M260:M:88:8:M602:"; > my $string_to_match = ""; > my $count = () = /\W$string_to_match\W/g; > print $count; > > output > > 0 > > If your colons weren't present at each end of the string then > it would still be possible, but slightly less tidy. Note also that > this is specifically for counting matches. If you want to > accumulate the matched contents into a list you would need > to bracket the string, as in > > my @match = /\W($string_to_match)\W/g; > my $count =- @match; > > otherwise the colons will be included in the aray elements.
Using a character class like \W won't work properly if $string_to_match is non-null. $ perl -le' $_ = ":B000:L520:M260:M:88:8:M602:"; $string_to_match = qr/\w+/; $count = () = /\b$string_to_match\b/g; print $count; ' 7 $ perl -le' $_ = ":B000:L520:M260:M:88:8:M602:"; $string_to_match = qr/\w+/; $count = () = /\W$string_to_match\W/g; print $count; ' 4 Better to use zero-width positive look-ahead and look-behind. $ perl -le' $_ = ":B000:L520:M260:M:88:8:M602:"; $string_to_match = qr/\w+/; $count = () = /(?<=:)$string_to_match(?=:)/g; print $count; ' 7 $ perl -le' $_ = ":B000:L520:M260:M:88:8:M602:"; $string_to_match = ""; $count = () = /(?<=:)$string_to_match(?=:)/g; print $count; ' 0 John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]