Mathematical Formula Validator

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pankajit09
    Contributor
    • Dec 2006
    • 296

    Mathematical Formula Validator

    Hi

    I want some mechanism to validate a mathematical formula.

    For eg: (a+b is not valid since the closing bracket is missing.

    Please help.
  • ronnil
    Recognized Expert New Member
    • Jun 2007
    • 134

    #2
    you will want to need regular expressions.

    start out here http://en.wikipedia.org/wiki/Regular_expression this covers the basics, afterwards you can find the functions working with regular expressions on http://www.php.net/manual/en

    Comment

    • pbmods
      Recognized Expert Expert
      • Apr 2007
      • 5821

      #3
      Regular expressions will do the job, though for the sake of your sanity, you'll probably want to use a stack-based parser instead.

      Run through your string and push an element every time you encounter an opening parenthesis/bracket. When you encounter a closing parenthesis/bracket, attempt to pop it off the stack. If the stack is empty, or if the next item on the stack doesn't match (e.g., trying to close a parenthesis before closing an inner bracket), you have an invalid string.

      Comment

      • Motoma
        Recognized Expert Specialist
        • Jan 2007
        • 3236

        #4
        Originally posted by pbmods
        Regular expressions will do the job, though for the sake of your sanity, you'll probably want to use a stack-based parser instead.

        Run through your string and push an element every time you encounter an opening parenthesis/bracket. When you encounter a closing parenthesis/bracket, attempt to pop it off the stack. If the stack is empty, or if the next item on the stack doesn't match (e.g., trying to close a parenthesis before closing an inner bracket), you have an invalid string.
        If all you are trying to do is check for parenthesis, just use the counting method: ( is +1, ) is -1. If at any point you are negative, you have a bad string. If you are at the end of the string, and you are not 0, you have a bad string.

        If you need to do other types of validation, a transformation to polish prefix notation makes numbers quite easy to work with in code.

        Comment

        • pankajit09
          Contributor
          • Dec 2006
          • 296

          #5
          I don't want only for parenthesis.

          I want for every case.

          Comment

          • Motoma
            Recognized Expert Specialist
            • Jan 2007
            • 3236

            #6
            In that case you are going to need to set up a formal document delineating the requirements of your system. Once you have these requirements you can come back if you have issues meeting them.

            Comment

            Working...