in reply to Regex to capture every readable character except COMMA
G'day nehavin,
Your first problem is your character class: those extra characters (e.g. parentheses) aren't doing what it looks like you're expecting them to do. See "perlretut: Using character classes" for details.
Beyond this, you've overcomplicated what's needed. You can use the regex as the condition and $var =~ /,/ will be true if $var contains a comma. Using !~, instead of =~, negates the result. Perhaps a review of "perlretut - Perl regular expressions tutorial" would prove useful.
You might also consider using transliteration (either y/// or tr/// — they're synonymous) which can provide a speed benefit if that's important. See "perlop: Quote-Like Operators" for details.
Here's some examples:
#!/usr/bin/env perl -l use strict; use warnings; my @vars = ('abc,d', 'abcd', 'a,b,c,d'); for my $var (@vars) { print "var = '$var'"; print 'm/,/: ', $var =~ /,/ ? 'not matches' : 'matches'; print 'y/,/,/: ', $var =~ y/,/,/ ? 'not matches' : 'matches'; print '! m/,/: ', $var !~ /,/ ? 'matches' : 'not matches'; print '! y/,/,/: ', $var !~ y/,/,/ ? 'matches' : 'not matches'; }
Output:
var = 'abc,d' m/,/: not matches y/,/,/: not matches ! m/,/: not matches ! y/,/,/: not matches var = 'abcd' m/,/: matches y/,/,/: matches ! m/,/: matches ! y/,/,/: matches var = 'a,b,c,d' m/,/: not matches y/,/,/: not matches ! m/,/: not matches ! y/,/,/: not matches
-- Ken
|
|---|