Tuesday, April 18, 2017

Now You Have Two Problems

Now You Have Two Problems

There’s a programming joke that goes like this
You have a problem and you think “I’ll use a
regular expression.” Now you have 2 problems.
Some people misuse regular expressions, but sometimes they are just what you need.
This Stack Overflow question involves parsing a string containing math operators and
integers. The answers ranged from simple to complex, and at least one answer required reading The Dragon Book.
In the spirit of “doing the simplest thing that can possibly work”, I present this regular expression
[()*/+-]|\d+
  • [()*/+-] means match one character from the set ()*/+-
  • the \d stands for a single digit and the + means appearing one or more times
  • the | is the logical OR
So the expression means "match one of these punctuation characters OR an integer number". It will silently ignore anything else such as whitespace, and this is exactly the behavior we want.

No comments:

Post a Comment