Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
expression parser

Posted by nano (nano), 15 September 2006
Hi guys

Anyone out there have a neat way to parse an arithmetic expression in C++.

It could be like command line expr ( A * B  ) / 2
Now I have the Arithmetic methods written that is multiple and add

but need a neat way to  parse the expression to pass the values into the Arithmetic methods ...

Any ideas out there .
all ideas appreciated
Thanks

Posted by admin (Graham Ellis), 15 September 2006
I would use the regex library ....

man regex

Code:
NAME
    regcomp, regexec, regerror, regfree - regular-expression library

LIBRARY
    Standard C Library (libc, -lc)

SYNOPSIS
    #include <regex.h>

    int
    regcomp(regex_t * restrict preg, const char * restrict pattern,
            int cflags);

    int
    regexec(const regex_t * restrict preg, const char * restrict string,
            size_t nmatch, regmatch_t pmatch[restrict], int eflags);

    size_t
    regerror(int errcode, const regex_t * restrict preg,
            char * restrict errbuf, size_t errbuf_size);

etc

Typically, the best way to parse arithmetic expressions such as you're writing about is to search for all the alphanumeric blocks and split the incoming stream into tokens based on those, then analyse each token.   I've done this is Perl ... starting with
@tokens = split(/(\w+)/,$line);
to give you a list of tokens - note the capture brackets around the regular expression which means that it will be saved into the @tokens list.

You then need to handle the brackets, etc, through a dijkstra shunt.  It's a long time since I wrote one of those!

We are running a Regular Expression Course on 13th October 2006 - a great place to learn if you've not come across them before, and we do have space available.

Note for anyone reading this page AFTER 13th October - click on the course link to find later dates; it's a regular course





This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho