
japhy
Enthusiast
/ Moderator
Nov 25, 2000, 8:36 AM
Post #2 of 3
(859 views)
|
|
Re: Newbie regex perplexity...
[In reply to]
|
Can't Post
|
|
You want to check to make sure they used only digits, hyphens, periods, parentheses, and spaces. You want to use a "negated character class". Negated just means "take the opposite of..." To match digits, hyphens, etc., you'd use [\d\s().-] which match either a digit, a whitespace, an open paren, a close paren, a period, or a hyphen. To get the opposite of that, you include a ^ as the first character of the class: [^\d\s().-] <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> if ($value =~ /[^\d\s().-]/) { print "bad value: '$value'\n"; } </pre><HR></BLOCKQUOTE> In fact, you could even tell the user what character was bad: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> if ($value =~ /([^\d\s().-])/) { print "bad character in '$value': '$1'\n"; } </pre><HR></BLOCKQUOTE> The parens around the character class will store whatever matches into $1 (or $2, or $3, depending on how many sets of parens you've used). If you want to tell the user about ALL the bad characters they put in their string, you can do: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> if (@bad = $value =~ /([^\d\s().-])/g) { print "bad characters in '$value': @bad\n"; } </pre><HR></BLOCKQUOTE> The g modifier to the regex makes it match as many times as possible, and since we're assigning the result of the pattern match to an array, the array will be filled with all the matches. For more enlightenment, read the 'perlre' documentation. ------------------ Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher
|