3 ms·
Well I think RE's are horribly over used. I think this comes from an unjustified fear about parsers or complete ignorance that they even exist by most programm
by ms4720 15y ago
Well I think RE's are horribly over used. I think this comes from an unjustified fear about parsers or complete ignorance that they even exist by most programmers. For example lets write a RE to recognize and extract a phone number, here is your spec: http://en.wikipedia.org/wiki/Local_conventions_for_writing_telephone_numbers http://en.wikipedia.org/wiki/Local_conventions_for_writing_t...
Have you screamed yet, for example in the US the exact same phone number can be written like so, some of the variants I have seen:
(516)-123-4567
1(516)-123-4567
1-516-123-4567
123-4567 old fashioned but valid
1.516.123.4567
now with a parser I can use RE for the simple bits that turn a text stream into bits of data and then hand it off to the to the parser to figure out if it is a good phone number. So the lexer, where the simple RE live, can turn a stream of text into a stream of tokens that the parser can reason about, for my US example above here is the list:
1: a string of digits called NUMBER and what they are
2: a ( called LP
3: a ) called RP
4: a - called DASH
5: a . called DOT
Then I can parse the 5 things above to figure out is it a valid phone number in nice readable and maintainable code.
Doing the above also makes you much more immune to changes in the RE libs behavior, I have gotten bit by greediness changes in perl before on bug fix releases because I did not follow my above advice. Another benefit is that in 6 months is that you can figure out what you did and so can the next guy
- kls 15y agoYou raise a good point, I tend to like them for parsing but they are not silver bullet for sure. They do have their weaknesses, that being said, when I use a regular expression, I always document it for myself and other developers, even if it is redundant information I document it, due to the fact that they are not readable and I tend to not like magic code.
- ms4720 15y agoDon't get me wrong I like REs, its just I like them like salt in my food. It is very easy to ruin the food by putting in too much salt, but put in the right amount and delicious.