posted
I've been learning Ruby and making good progress. The manual from which I've been learning, however, gave me a more cryptic piece of code than usual:
The problem is that while I get the rest of this program, this line I don't, and I can't seem to find information elsewhere on it. Any Ruby guru here would be kind enough for a quick answer?
Posts: 3060 | Registered: Nov 2003
| IP: Logged |
posted
It's an input mask for a phone number using regular expressions. The first three digits are surrounded by parentheses (which have been escaped out with backslashes), and the \s is a check for whitespace. The phone number is divided into three groups -- area code, three digits, and four digits -- by non-escaped parentheses, and the \d{#} indicates how many digits are in each group.
posted
On a more general note, while regular expressions are powerful and useful, they suffer from 'everything looks a nail' syndrome.
For instance, if parsing user submitted phone numbers is what's in question, it is better to normalize by stripping all non-numeric digits, then do a check against the requirements for valid phone numbers (which can just be a length check in the naive case), rather than requiring users to submit in a particular pattern.
Regular expressions are also frequent sources of errors in programs, particularly for beginners. Making the logic involved more explicit can make a program much more maintainable, as well.
This isn't to say there aren't excellent times to use regular expressions, just that it is very easy to over-use them.
Posts: 15770 | Registered: Dec 2001
| IP: Logged |
quote:Originally posted by HollowEarth: What fugu means is don't do things like at the bottom of this page.
I don't know. The regular expression seems decent for what it's being used for, which is simply expressing a standard. No one is suggesting that it should be a practical implementation (I hope).
Still, that was an impressively long and cryptic expression. Sounds like it belongs somewhere in the International Obfuscated C contest.
Posts: 2437 | Registered: Apr 2005
| IP: Logged |
posted
I suspect a properly written parser would be better and faster at validating a standard, as well as considerably more readable for understanding it .
Posts: 15770 | Registered: Dec 2001
| IP: Logged |