Parsing an Algebraic Expression

Hi ,
Can any body provide me an idea to parse an algebraic expression in Java.Are there any built in classes for parsing an expression and evaluating after substituting the values for variables in the expression?
If no classes are availble,plz provide me any algorithm for doing that.
Thanks in Advance

Observe:
Parsing an expression is essentially the act of converting the expression from infix notation to postfix notation. Infix requires parens and precedence to specify order of operations but post fix unambiguously specifies them by the order of the tokens
So something like
"a+b*c" becomes "a b c * +"
"a*b+c" becomes "a b * c +"
"(a+b)*c" becomes "a b + c *"
notice that arguments (variables and numbers, the leaves of the implied expression tree) occur in the same sequence in both the infix and the postfix notation. Thus you can view the parsing as a filtering process that passes arguments directly from input to output and all the filter is doing is re-arranging the order of the operators.
All this rearranging of operators can be done with a single stack and it is all based on this observation:
When you saw a string like "a op1 b op2 c" you run across the token for the first operator before you have even collected its right argument. You must put that operator somewhere and a OpStack is the place to put it. You don't know whether to emit op1 until you have had a look at the next operator, op2. If op2 was higher priority than op1, then op2 gets to consume the argument b first. In that case op2 just gets added to the stack on top of op1.
However if op2 was less than or equal in precedence to op1, well then op1 can now be flowed to the output stream and allowed to act on the b argument that is already out on the output stream.
This means that the fundamental operation of the expression parser is the business of pushing an opertor token onto the stack, but first spewing to the output all the other operators on the stack that had a higher or equal priority. If we give this function a name like opStack.pushSpew(token) it could look something like this:
class OpStack{
  Stack s = new Stack();
  void pushSpew(List out, Token t){
    Token tos;
    while(!s.empty() && (tos = peek()).priority >= t.priority){out.add(pop());}
    push(t);
}Next thing to observe is that a grouper, like open and close parens, behaves in the following way. An open paren acts like a very high priority operator when pushed to the stack in that it spews nothing. The previous op is NOT allowed to eat the argument that is about to come right after the open paren. However once the open paren marks the stack, the open should be a lower priority than any real op that gets pushed onto the stack above it because it must delay going out until every real op in the group had its shot. The close paren should also act like a very low priority op. It should spew every op upto but not including the open paren that started this group.
As a computation trick, if you set the priority of an open lowest of all, and the priority of a close just above that, and you just push the open onto the stack instead of pushSpewing it onto the stack, you will get the desired behavior. You with then pushSpew the close paren and it will dump everything from the stack to the output up to but not including the open. At this point it is easy to check the balance. If you do not have an open/close pair sitting as the top two elements on the stack then the parens (or the brackets or the braces) were not properly nested.
We are almost done. There are post fix operators like factorial and prefix operators like minus that we need to deal with. It only makes sense to evaluate these suckers from the inside out i.e. if you had a string of prefixs on an arg
op1 op2 op3 arg
the only sensible order is defined by parens like this
(op1 (op2 (op3 arg) ) )
and in post fix that would be
arg op3 op2 op1
that is exactly what you would get if you just pushed each prefix op onto the stack in the order you saw them and then popped them off after you dumped out the argument.
Post ops should also work from the inside out
arg op1 op2
being
( (arg op1) op2 )
and you get this behavior by just dumping a post op to the output when you see it.
There is only one special concern. What should you do if you saw, both pre ops and post ops on the same arg?
is "op1 arg op2" done like this: "(op1 arg) op2" or "op1 (arg op2)"? Well, why should these be any different from regular diadic ops, let precdence decide. An espression like minus three factorial "-3!" should be interpreted as take the factorial of 3 and then negate it (and not the other way around!) so let the priority of factorial be greater than that of minus and just do the standard pushSpew with post ops to let them spew out any high priority pre ops before they go onto the stack, but then unlike binary ops, the post op immediately comes off the stack and goes to the output because post ops bind up right away.
Now if you are not careful with your precedences you could get "wierd" behavior. If for example you did not assign a high priority to a factorial, you could write expressions like "3+4!" and the priority would treat that like "(3+4)!" the plus would bind tighter than the factorial. It is hard for me to imagine a language where you would want the effects of either a postfix or a prefix operator to span across multiple arguments combined by single diadic operator, but that is really up to you. You certainly could have a language where you gave a very low precedence to ~ which could mean the boolean NOT, a lower precedence than the diadic operator >= which would allow you to write "~ a >= b" which would mean "~(a>=b)"
After all it is your language, do what you want. None the less I would advise against alowing ANY pre or post op to have a priority LESS than that of ANY diadic operator.
Lots of talk here but to recap, the code is quite simple:
while((t = getNextToken()) != null){
  switch (t.type()){
    case ARG:  out.add(t); break; // arguments pass straight to output
    case PRE:  stack.push(t); break; // pre ops are just pushed (binding them to the next arg)
    case OPEN: stack.push(t); break; // Opens just push, they don't spew to output
    case DI: stack.pushSpew(out,t); break; // Diadic ops do the standard pushSpew
    case POST: stack.pushSpew(out,t); out.add(stack.pop()); break; //spew and then go out
    case CLOSE: stack.pushSpew(out,t); stack.removeOCpair(); // spew all ops in group
      // and then check if you had a balancing open
}That just about does the entire parse. If you can find the tokens in the input you can rearrange them into the output. You do need to flush the opStack when you are done with the input stream and there is a convenient trick to doing that. The trick is this. Invent an invisible Open and Close pair, invisible meaning that they never show up in any input stream, you just made them up and pretended that that expression started with an invisible OpenExp and at the end it closed with a CloseExp.
The CloseExp at the end will act like any grouper, it will flush the stack looking for the corresponding opener. IF there was any unbalanced grouper, like say an extra unbalanced open paren somewhere in the expression, the CloseExp will spew its way down to that unbalanced paren and then fail when it discovers that it does not match the open in the call to remove the OC pair. The is a way to do error detection. Use a fictional group on the entire expression to both flush the remainder of the opStack and to do a final check for unbalanced groupers.
In fact, while we are on the topic of error checking there is another one that is very good to include. Basically in a real expression if you ignore the parens, the progression should be an alternation between args and diadic ops, with an occasional pre or post op thrown in.
A simple count tells you where you are. Go up to 1 when you pass an argument, go back down to zero when you see a diadic operator. You should start at zero, because there have been no arguments or ops yet. In state zero the only legal things to do are to put in a pre op or an arg. Once you have an arg out there the only legal things to do are to have a post op or a diadic op. This little state machine will tell you if and when you have got either a pair of arguments together with no op between them, or a pair of ops with no argument between them. You should start at state = 0 and you should end at state = 1 (unless you allow empty expressions) So we can beef up the error checking with a very simple addition. The guts of the parse will now look like this:
state = 0
stack.push(Token.OpenExp); // start off with an open of the expression
while((t = getNextToken()) != null){
  switch (t.type()){
    case ARG:  assertStateIs(0); out.add(t); state = 1; break;
    case PRE:  assertStateIs(0); stack.push(t); break;
    case OPEN: stack.push(t); break;
    case DI: assertStateIs(1); stack.pushSpew(out,t); state =0; break;
    case POST: assertStateIs(1);stack.pushSpew(out,t); out.add(stack.pop()); break;
    case CLOSE: stack.pushSpew(out,t); stack.removeOCpair();
stack.pushSpew(out,Token.CloseExp); stack.removeOCpair();
assertState(1);
return out;So - there it is, in outline form the way that you parse an expression.You build 3 classes, Token, ExpressionParser, and OpStack
Token is just a bucket that holds a name, a type (ARG, PRE, OPEN, DI, ...) and a precedence.
OpStack is just a wrapper for a reqular stack that will hold Tokens and allow for a pushSpew function.
ExpressionParser is little other than a Map full of all your Tokens. This map allows the parser to map substrings, tokens, that it finds in the input like >= to actual Tokens with a capital T. It will have two main methods:
1) the parse method which I have almost completly written for you. It takes an input string and will fill up an output list placing the Tokens in post fix order, which is your parse tree.
2) the routine getNextToken which will walk the input string, skipping white space when appropriate, looking for names, numbers, and operators and building each chunk that it finds into a Token.
One last complexity note. If you want to allow functional notation like sqrt(3) you are using parens in a fundamentally different way than was described above (ditto when you use brackets to represent array indexing like x[5]) the fundamentally different thing that you are doing is that you are allowing an argument (a name) like "sqrt" to sit right next to another argument like "3" with no binary op in between. You are using an "implied" binary op at that point. You have saved the user from typing "sqrt FUNCTIONCALL (3)" or "x ARRAYINDEX 5"
I will leave it as an exercise to the reader to see how you make a small modification to the OPEN case to detect and deal with an implied operation. Don't forget that you must tell the state error checker what you are doing.
And now that I have shown you how fundamentally simple it is to build an expression parser let me comment on why you do not find a standard library routine for doing this.
The primary reason is that there is no such thing as a "standard" math expression. Parsing is based on a language and there is no one language. Are you going to allow hex numbers in your expressions? How about scientific notation? Is = equality or assignment? Do you allow functional notation? Array indexing? Multi-dimensional array (like x[2,3])? How about string constants like "foobar"? How do you embed quotes in your quoted strings? Are you allowing comments, block comments, statements, code, Lisp expressions, complex numbers, implicit type conversion, type casting? At what point does it stop being a simple expression and start being a full computer language?
Furthermore, most of the work you will quickly see if you use what I have suggested to build an expression parser, it how to give your user feedback that the expression that he typed had problems and where. There is no stardard UI for error feedback in things that don't parse correctly. Are you just going to dump cryptic strings to the console or are you going to highlight something in a text box somewhere?
All the work turns out to be that of defining your language and determining your set of tokens and what precedence you will employ. Once you get that all worked out, parsing the expressions only takes the ten or fifteen lines of code that I outlined.
And look, it only took several thousands of words to explain why it only takes about 15 lines of code to parse expressions once you have decided upon your language and written your tokenizer.
Enjoy

Similar Messages

  • Binary tree for parsing algebraic expressions

    hi all
    i have a project to do.. i need to read in an algebraic expression, parse it and form a binary tree. later use that tree to evaluate the expressions when the actual value for those variables are passed..
    can anyone tell me how to go about doing this.
    im a beginner in java..
    tks

    first of, your going to need three stacks. The implementation of a stack in JAVA is something that's easy to find, do a forum search. Your going to need a Binary Node as well. One stack will hold the operator elements of your algebraic expression, another will hold the numeric values, and the final will hold your binary nodes:
    expression: 4 + 6 - (6 * 9)
    now there are some rules that should be followed. Whenever a closing parenthesis is encountered ")", pop an operator, pop two numbers, and create the corresponding binary node.
    order of operations:
    push 4 onto numberStack
    push + onto operatorStack
    push 6 onto numberStack
    push - onto operatorStack
    push ( onto operator Stack
    push 6 onto numberStack
    push * onto operatorStack
    push 9 onto numberStack
    ")" encountered
    Now, your stacks look something like this:
    operatorStack: [ +, -, (, *, ) ]
    numberStack: [ 4, 6, 6, 9 ]
    pop 9 and 6 from numberStack, pop * from operatorStack
    build a binaryNode using these three elements
    push this node onto the binaryNodeStack
    I.E. using the expression above:
    / \ is the resulting binary node once the ")" is received.
    6 9
    etc.. there are some rules regarding when to pop and build binary nodes, it's been a while since i did this assignment and frankly my brain hurts, hope this gets you started, good luck.

  • Parsing a java expression

    Write a program in Java that can parse a mathematical expression
    String, calculate the expression, and produce a numeric result.
    For example, given the string: "2.5+3*4+6/12-7" produce the result 8.0
    Requirements: Parser
    * expression can contain Integers or floating-point numbers
    * expression can contain Operators for addition, subtraction, division
    and multiplication
    * parser should throw an Exception when the expression is invalid
    Requirements: Solution
    * Implement the solution in Java
    * Compile and test the solution
    * The solution should demonstrate good modularity, be self-contained,
    reusable and extensible.
    * The solution should be clearly written, easy to read, documented, and
    production-quality.
    Requirements: quality
    * This is a timed exercise and should be completed quickly, however you
    should take sufficient time to produce a quality result
    * A quality solution is simple, concise, complete, well documented,
    readable, adaptable, reusable, testable and robust.

    If your assignment was to:
    1) figure out how to create a login on the forums
    2) cut-and-paste verbiage given to you by someone
    3) create a topic in the forums with the above
    then you get an 'A'. Congratulations!

  • How can i perform operations on a string written as an algebraic expression

    i need help...how can i have a program that a string like this ---"1 + 2 + 3"---could be read as integers and you can actually come to a single result using the precedence of operations...

    epoy wrote:
    i need help...how can i have a program that a string like this ---"1 + 2 + 3"---could be read as integers and you can actually come to a single result using the precedence of operations...That's not as easy as it sounds.
    If you only have fairly simple mathematical expressions have a look at:
    - if you have JDK 1.6, see reply #7 [http://forums.sun.com/thread.jspa?threadID=5144807]
    - or if you have JDK 1.5 (or less), have a look at reply #12 from the same thread.
    If you need more fancy math functions, Google for "JEP", or "mathematical expression parser".
    Good luck.

  • Java parser for regular expression to java program

    Hi All,
    I am very new to parser technologies .I am looking for a (java)parser which can read the "regular expression" and can convert it into "java program".Please let me know is there any thing related to this.
    Thanks in advance.
    Your will be appriciate.
    Regards,
    Sai.

    Hi Jos,
    Thank you for your quick response .You're welcome.
    If you have any sample code or simple example for how to use those
    classes (Pattern,Match) ,will you please send me .It will be helpful for me.Jverd gave you two nice links already in his reply #3
    If there is any "open source" for parsering regular expressions.
    Please send me I am very new to parser technologies.Note that that Pattern class take care of all the parsing of REs, i.e. there's
    nothing 'interesting' left for you to do any parsing whatsoever. Can you
    elaborate a bit on what you exactly want to do and learn?
    kind regards,
    Jos

  • Parsing with regular expressions

    Hi
    I'm developing an application that is trying to parse a text in a text file. It's looking for strings like
    " 0551 TIMERHIN, S.L. "
    Then I think I could lok with matches method for a string with many white chars followed by 4 numbers...
    I did
    line.matches("^\\s+[0-9]{4}")
    but it didn't work...
    Any help will be appreciated.
    <jl>

    The String.matches tries to match the regular express against the whole string.
    You regex pattern "^\\s+[0-9]{4}" will match
    "                          0551"but not
    "                          0551 TIMERHIN, S.L. "You can do it using this code:
    import java.sql.*;
    import java.io.*;
    import java.util.regex.*;
    import java.util.*;
    public class RegExTest {
    public static void main (String args[]) {
       Pattern pat = null;
       Matcher m = null;
       String patternToMatch = "^\\s+[0-9]{4}";
       pat = Pattern.compile(patternToMatch);
       System.out.println("Pattern to match = " + patternToMatch);
       String line = "                          0551 TIMERHIN, S.L. ";
       m = pat.matcher(line);
       if (m.find()) { System.out.println("Line matched"); }
    } // end main
    } //End Class Test
      

  • Parsing an arithmetic expression

    Hi,
    I'd like to get the result of an arithmetic expression. I found some algorithms which describe how to get the result of an expression with parens and the four basic operations (+, -, *, /). Now I want to do this to an expression with all the operations you can find on a scientific calculator, for example sin, cos, log, ^, sqrt, nCr, ! ...
    I mean something like this:
    sin(2x)*sqrt(8.5x/1.25)+5/x^3-x^(2-5x)-5!
    The algorithm would have to return -123.1322 in this case.
    Does anyone know how normal calculators does this? I am more interested in the basic idea and not the coding itself.
    I thought about something like this:
    solve(expression)
       do until there is a result:
          if there are no other operations in the expression than +, -, *,/ and parens, then:
             calculate the result and return it
          else:
             search the first operation which is not +, -, * or / , for example sin(...)
             get the caption in the brackets
             solve(caption in the brackets)      <--- recursive functionDo you have a better idea? I am nor sure this is a good algorithm.
    DrummerB
    Edited by: DrummerB on Feb 28, 2008 5:30 PM

    Hello DrummerB,
    I reckon that without getting into the theory (which I recommend), the simplest way to achieve the goal is using cascading.
    1. Order all operations by precedence, example:
    operators | precedence
         +, - | 0
         *, / | 1
            ! | 2
            - | 3 (unary minus)2. Create a parsing/solving algorithm, example:
    solveExpr(e)
        ts := token stream for e
        return solveAdditiveExpr(ts)
    solveAdditiveExpr(ts)
        left := solveMultiplicativeExpr(ts)
        while next token in ts is "+" or "-"
            right := solveMultiplicativeExpr(ts)
            if next token in ts is "+"
                left := left + right
            else
                left := left - right
            consume next token in ts
        return left
    solveMultiplicativeExpr(ts)
        left := solveFacultyExpr(ts)
        while next token in ts is "*" or "/"
            right := solveFacultyExpr(ts)
            if next token in ts is "*"
                left := left * right
            else
                left := left / right
            consume next token in ts
        return left
    solveFacultyExpr(ts)
        left := solveUnaryMinusExpr(ts)
        while next token in ts is "!"
            left := faculty of left
            consume next token in ts
        return left
    solveUnaryMinusExpr(ts)
        negative := false
        while next token in ts is "-"
            negative := !negative
            consume next token in ts
        if negative
            return -number(ts)
        else
            return number(ts)
    number(ts)
        the next token in ts must be a number, consume and return itExample:
    e := "10 + -5 / 3 * 5! - - - - -7"
    => ts := <10, "+", "-", 5, "/", 3, "*", 5, "!", "-", "-", "-", "-", "-", 7>
    solveExpr(e) = (10 + (((-5) / 3) * (5!))) - 7 = -197With kind regards
    Ben

  • Parse using regular expression

    public static void main(String[] arg)
              String s = "0; url='http://www.google.com'";
              String pattern = "^\\s*[0-9]+\\s*;\\s*url\\s*=\\s*(�|'|")*(.*)(\"|'|�|")$";
              Pattern p = Pattern.compile (pattern);
              Matcher m = p.matcher(s);
              if(m.find())
                   System.out.println(m.group(2));
              else
                   System.out.println("not found");
         }In the sample code above, http://www.google.com will be displayed. I want to update the pattern such that if the URL is not within a single quote, it should still display the correct string.
    e.g. String s = "0; url=http://www.google.com"; The above pattern fails when URL is not within single quotes.
    Could someone please help me.
    Thanks

    Thanks. However, the pattern you have given retains the " character in the output.
    e.g. String s = "0; url=http://www.google.com'"; In this example, there is a single quote at the end of the URL. Your pattern retains this in the group I am printing out, i.e. when I print out, I get the output http://www.google.com'.
    If a single or double quote is there, the pattern should ignore it.

  • Parsing EL expression in custom tag 10.1.3.4

    Hello all,
    I have a custom tag that extends CoreOutputTextTag. This tag needs to resolve the El expression passed in from the value attribute and perform an operation with it. Since I this tag needs to work with adf 10.1.3.4, the jsp level is 1.2 and does not support container parsing of EL expression directly in the page ($).
    I have tried a couple approaches but both of them result in just the same EL expression I pass in being returned to me. Anyone have an idea of the proper way to resolve an EL expression within a custom tag?
    Thanks in advance,
    - Joe
    public class CoreOutputTextTag extends oracle.adfinternal.view.faces.taglib.core.output.CoreOutputTextTag {
        private String groupId;
        private String groupCode;
        private String value;
        public void setValue(String value) {
            this.value = value;
            super.setValue(value);
        public int doStartTag() throws JspException {
            super.doStartTag();
            UIComponent uiComponent = this.getComponentInstance();
            if (uiComponent instanceof CoreOutputText) {
                CoreOutputText coreOutputTextComponent =
                    (CoreOutputText)uiComponent;
                if (coreOutputTextComponent.getValue() == null) {
                    String codeValue =
                        (String)ExpressionEvaluatorManager.evaluate("value", value,
                                                                    java.lang.String.class,
                                                                    this,
                                                                    pageContext); // the page context
                    try {
                        ExpressionEvaluator expressionEvaluator =
                            pageContext.getExpressionEvaluator();
                        codeValue =
                                (String)expressionEvaluator.evaluate(value, java.lang.String.class,
                                                                     pageContext.getVariableResolver(),
                                                                     null);
                    } catch (ELException elex) {
                    SystemSettingRow row =
                        SystemSettings.getSystemSettings(groupId, groupCode, null,
                                                         value);
                    if (row != null)
                        coreOutputTextComponent.setValue(row.getShortDesc());
            return TagSupport.SKIP_BODY;
        public void setGroupId(String groupId) {
            this.groupId = groupId;
        public String getGroupId() {
            return groupId;
        public void setGroupCode(String groupCode) {
            this.groupCode = groupCode;
        public String getGroupCode() {
            return groupCode;
    <tag>
      <name>coreOutputText</name>
      <tag-class>od.adf.ics.ui.taglib.CoreOutputTextTag</tag-class>
      <body-content>empty</body-content>
      <attribute>
       <name>groupId</name>
       <required>true</required>
      </attribute>
      <attribute>
       <name>groupCode</name>
       <required>true</required>
      </attribute>
      <attribute>
       <name>id</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>truncateAt</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>description</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>escape</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>shortDesc</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>partialTriggers</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onclick</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>ondblclick</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onmousedown</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onmouseup</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onmouseover</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onmousemove</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onmouseout</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onkeypress</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onkeydown</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>onkeyup</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>styleClass</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>inlineStyle</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>value</name>
       <rtexprvalue>true</rtexprvalue>
      </attribute>
      <attribute>
       <name>converter</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>rendered</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>binding</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
      <attribute>
       <name>attributeChangeListener</name>
       <rtexprvalue>false</rtexprvalue>
      </attribute>
    </tag>

    I also would like to know how to accomplish this. I have a similar requirement and need to set the "disable" attribute on a commandbutton and requires an el statement that calls a methodAction defined on the pageDef.
    I followed the great instructions over on this thread:
    ADF FACES:Creating custom component on top of adf
    on how to create custom adf tags for JDeveloper 10.1.3.4.
    many thanks!
    Wes
    Edited by: Wes Fang on Sep 16, 2010 5:39 AM

  • Using jaxen to parse xpath expressions

    Hi,
    I want to parse this XPath expression with jaxen: +$X//employee[@id=0529]/salary+
    after parsing i got this: +$X/descendant-or-self::node()/child::employee[(attribute::id = 529.0)]/child::salary+
    Jaxen doesn't parse +//employee+ as I expected.
    Is descendant-or-self::node()/child::employee equivalent to descendant-or-self::employee ?
    Edited by: basti on Oct 28, 2007 2:02 PM

    If I had to choose whether I think Jaxen interprets the XPath specs correctly or whether you do, I would choose Jaxen. But if you don't think so, wouldn't it be better to ask questions about Jaxen on the Jaxen mailing list?

  • Plisp: Lisp/S-expression parser library

    Plisp is a C library for parsing Lisp/S-expressions. I wrote it because I got massively sick of writing the same code every time I wanted to parse a text file.
    I'd like some testers/users for this. It suits *my* needs, but I'm not too good at accommodating other people's. Do give it a try.
    Installation:
    I decided to mix it up and use Mercurial instead of Git. I'm liking the change.
    AUR package is here: http://aur.archlinux.org/packages.php?ID=35422
    hg clone URI (also web view): http://peasantoid.org:1024/plisp
    Manual installation:
    $ root=/path/to/root_directory ./make install
    Documentation:
    Sorely lacking. I will attempt to write some of this later; in the meantime, look at the source (particularly header files) and everything in test/.
    Technical details:
    Text is processed in two stages. The first, tokenization, iterates through the text looking for 'simple' tokens (left/right parentheses, quotes, numbers, strings, symbols, etc.). The second, parsing, iterates through the token list and converts it to a parse tree.
    POSIX ERE (extended regular expressions) are used for tokenization. Seriously, this is really handy. $(man 3 regex) for details.
    Linked lists are heavily relied upon.
    Note that numbers are just stored as strings. It's up to the programmer to change those to actual numbers (f.e. strtol(), strtod()).
    Testing:
    The distribution includes a simple syntax-dumper utility that takes data from stdin, parses it, and formats the resulting syntax tree to stdout. My terminal transcript follows:
    narch plisp -> ./make test && build/test/dump
    ---[RUN test (lib)]
    ---[RUN lib (obj)]
    ---[RUN obj ()]
    build/obj/error.o
    build/obj/escape.o
    build/obj/init.o
    build/obj/list.o
    build/obj/parser.o
    build/obj/tokenizer.o
    ---[END obj]
    build/libplisp.so
    build/libplisp.a
    build/include/*.h
    ---[END lib]
    build/test/dump
    ---[END test]
    (foo '("bar") `(3.456 ,(baz 4 5)))
    ^D
    1:1 list: ...
    1:2 symbol: foo
    1:7 list (quoting: '): ...
    1:8 string: bar
    1:16 list (quoting: `): ...
    1:17 real: 3.456
    1:20 list (quoting: ,): ...
    1:21 symbol: baz
    1:25 integer: 4
    1:27 integer: 5
    Tested by/on:
    me: Arch 64-bit (x86_64 Intel Core 2 Duo (Apple MacBook3,1))
    me: Arch 64-bit (x86_64 Intel Xeon (Xen))
    me: ArchPPC (32-bit PowerPC processor (Apple Mac Mini G4))
    If you test this, please post your architecture and processor type. I really hate those insidious system-specific bugs.
    Last edited by Peasantoid (2010-03-13 05:31:46)

    Peasantoid wrote:Interesting thing I discovered: you have to pass '-lm' to GCC in order to get it to link with the math functions. Does anyone know why this isn't in libc?
    I've encountered this before, it's one of those things that make you go "huh?". Nice work on getting the math module done
    As a suggestion, it would be useful to have a module which allows loading and running arbitrary functions from shared libraries, although I'm not too sure where to start with implementing this, I think there is a library around that allows you to do this fairly easily, but I can't seem to find it right now. But as a relatively new scripting language something like this would make it easier to interact to common libraries while other modules are still being written.
    Edit: Obviously I was searching for the wrong thing, what I'm talking about is a foreign function interface
    Last edited by HashBox (2009-06-13 01:43:44)

  • Boolean Expression Parsing

    Hi
    i have a String like "true && !true && (false || true)" and want to know if the expression is true or false. Is there any Helperclass that parses an boolean expression??
    String expression = "true && !true && (false || true)";
    boolean result = BooleanParser.parse(expression );
    Regard,
    Harald

    thats not cheating, just the simplest way to solvethe problem ;)
    ... and one missed opportunity to learn something
    about parser generators.I think there is something to be said for taking classes on that particular subject.
    That particular study area is well defined in computer science is well defined. So the good ideas that one can use are already there just waiting to be learned.

  • Regular Expression Help

    I need help writting a regular expression that will match the following strings:
    1+1,1+(1+1),((1+1)+(1+1)),1+(1+(1+1)). Basically one that will match an arithmetic expression (operands limited to 1's and operators to '+' sign) with or without correctly matched parentheses. Have'nt had much luck so far. Any input will help. thanks

    okay, you asked for it:
    [1+()]+
    it will only match those string but it will tell you nothing about syntactically correct expressions. This is because these types of expression are not "regular" and cannot be properly parsed using regular expressions.

  • Comparing xpath expressions

    I would like to be able to compare two xpath expressions and evaluate whether their result CAN have nodes in common.
    For example:
    expression 1: /ItemData[@ItemOID='A']
    expression 2: /ItemData[@ItemOID='B']
    would need to evaluate to 'false'
    Other example:
    expression 1: /ItemData[@ItemOID='A']
    expression 2: /ItemData[@ItemOID='B or @ItemOID='A']
    would need to evaluate to 'true'
    Other example:
    expression 1: /ItemData[@ItemOID='A']
    expression 2: /ItemData[not(@ItemOID='B')]
    would need to evaluate to 'true'
    Other example:
    expression 1: /ItemData[@ItemOID='A']
    expression 2: /ItemData[not(@ItemOID='A'][not(@ItemOID='B']
    would need to evaluate to 'false'
    P.S. Sorry if the Xpath expressions do not show up 100% correctly in the above snippets - the editor is doing crazy ...
    I would like to do such an evaluation without actually having an XML document (!).
    Is this possible?
    Did someone ever write a class for doing so ?
    Many thanks
    Jozef

    XML4Pharma wrote:
    Is this possible?As phrased probably. You would need to create a xpath parser then compare the parse trees for expression equivalency.
    You might be able to find a xpath parser. The other part you would need to create yourself.

  • Parsing an xml document using  XPATH

    Hello,
    I am pretty new to programming "Java and XML" and right now very confused with the range of available xml parsers,xpath engines and xslt processors.I need some guidance on how to parse a xpath expression with variables in it .
    Thanks,
    Chan.

    Gregory . Thank you so much for the insight into parsing and xpath expression evalaution . I downloaded the XpathExamples.java file , practical xml jar file and executed the program to see the output for various example functions that you have created .All of them worked perfectly without any issues.
    In the variablesExample() function , I added the following lines to check if it works :
    variables.put(new QName("myvar"), "foo");
    System.out.println("myvar bound as 'argle' = " + xpath.evaluate("/$foo/bar/baz", dom));
    I ran into exceptions like ..
    Exception in thread "main" javax.xml.transform.TransformerException: Extra illegal tokens: '$', 'foo', '/', 'bar', '/', 'baz'
    Can you please tell me what was I doing wrong ? I am also planning to use starts-with() function in xpath expression . Will it work ?
    Thank you for your reasoning.

Maybe you are looking for

  • Ram Issues

    I Have 2 sticks of ram worked fine together for 3weeks running at ddr400. Today I restart my system and I get a nopost. I check the lights and I have  Early Chipset Initalization. Also I can boot and use the computer with 1 stick of ram out tested wi

  • CVD and ADC accounts are not getting credited during the Goods Receipt of Imports PO (India)

    Hello team, We are receiving the goods against with the Imports PO. Before the GR, we have paid the Customs duties to the Indian government. And, in the Invoice of Customs (MIRO), the CVD and ADC G/L Accounts got debited with the respective Accrual A

  • I have installed Firefox 4 but the "New Tab" button has disappeared. I have searched toolbars etc. but can't see it. Any ideas, please?

    My "New Tab" button has disappeared off the toolbar. I have searched the toolbar menus and "Customise Toolbar" but it's just not there. Back, Forward, Stop and Reload buttons are all there.

  • Have you ever needed dynamically evaluated Java?

    It seems every day or so someone asks how to evaluate/execute a piece of Java contained in a String, or evaluate a mathematical expression in a String. I've never needed this, so I'm curious - other than for academic purposes, who has ever needed to

  • WAD Variables?

    Hi Expert's, I have inculed the report to a WAD.But when I execute that in WAD the variables which should be shown as a range is not appearing .I mean to say beside the Variables I am getting drop down box on which all symbols like between,greater th