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
Python, Lua and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Java, C, C++, Ruby, MySQL and Linux / Tomcat systems
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

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

man regex

    regcomp, regexec, regerror, regfree - regular-expression library

    Standard C Library (libc, -lc)

    #include <regex.h>

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

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

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


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 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., 2018: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: • WEB: • SKYPE: wellho