Evaluating a string expression.

hi,
If have a string,which is an expression. how can i evaluate in java.
for example
" Monday in (Monday,Sunday,Tuesday) *And* 25 > 20 *OR* 9:00 between 8:00 and 10:00"
Is there any api to evaluate the above the expression to give a Boolean value

no. you have to:
1/ create an interface "Criteria" with a single method "boolean parse();" defined in it
2/ for each kind of expression, create a class implementing criteria, with a string as parameter in the constructor, and implements the parse() method so as it will be able to return "true" when the result of the expression is true, and false otherwise
3/ when 1/ and 2/ are done, you can easily parse the complete expression (expr1 AND expr2 OR expr3) by splitting the complete expression on "AND" and "OR" statement, check what kind of criteria is expr1, expr2, and expr3, create the criteria by passing the expression as a parameter in the constructor of the appropriate class, call parse
4/ make the sum of every parse() result
if you're a java beginner, i suggest that you come back to this exercise later ; it won't be easy

Similar Messages

  • Evaluating a String

    Hi,
    I'm trying to find a means of evaluating a mathematical expression contained within a String. For example, the string might be:
    4*2 + (34/(4 -3)), where the output of the function is a solved numberical value, in this case 42.
    I haven't been able to find anything in Java, although functions like this exist in javascript and even BBC basic (EVAL). Does anyone know where I can find something like this?
    Cheers,
    Pete Frederick

    You need to parse it. The easiest thing to do is converting it to postfix and then evaluating. Note that the eval function works in JavaScript because it is interpreted and not compiled. I'm sure there are lots of examples to be found on the web that do this.
    Kind regards,
      Levi

  • Evaluate String Expression

    Hi all,
    I am trying to evaluate a string expression against rows of data. If the data satisfys that condition/expression then its selected otherwirse its not.
    To re-iterate how to evaluate a string expression like: "value < 1"
    against data values like: 0, 1, 2 ...n
    Any help will be appreciated. Thanks in advance.
    Here's the code I am using:
          * Evaluates the Expression Either return True or False
          * @return
      public boolean evalExpression() {
              boolean retval = true;
              // Identify the conditional process step
              if (this.isConditional()) {
                   // get the inputs
                   for (int i = 0; i < myInputs.size(); i++) {
                        ContainerDataElement containerDataElement = (ContainerDataElement) myInputs
                                  .elementAt(i);
                        String data = containerDataElement.getValueAsString();
                                            // Get the conditions
                        for (int j = 0; j < myProcessConditions.size(); j++) {
                             ProcessCondition pc = (ProcessCondition) myProcessConditions
                                       .elementAt(j);
                                  Boolean condition = new Boolean(pc.getExpression());
                                                      // Evaluate the expression against the data elements
                             if (condition.booleanValue()) {
                                  retval = true;
                             else {
                                  retval = false;
              return retval;
         }

    ProcessCondion holds the Expression but I need to match the value the expression matches.
    A bit like equals example I am trying out now:
      public boolean evalExpression() {
              boolean retval = true;
              // Identify the conditional process step
              if (this.isConditional()) {
                   // get the inputs
                   for (int i = 0; i < myInputs.size(); i++) {
                        ContainerDataElement containerDataElement = (ContainerDataElement) myInputs
                                  .elementAt(i);
                        String data = containerDataElement.getValueAsString();
                        com.aim.common.DebugLog.debug("dataELEMENTS--------"
                                  + data.toString());
                        // Get the conditions
                        for (int j = 0; j < myProcessConditions.size(); j++) {
                             ProcessCondition pc = (ProcessCondition) myProcessConditions
                                       .elementAt(j);
                             com.aim.common.DebugLog.debug("ProcessCondition--------"
                                       + pc.toString());
                             Boolean condition = new Boolean(pc.getExpression());
                             com.aim.common.DebugLog.debug("condition--------"
                                       + condition.toString());
                             // Evaluate the expression against the data elements
                             if (containerDataElement.equals(condition)) {
                                  com.aim.common.DebugLog.debug("conditionEVALUATED--------"
                                            + retval);
                                  retval = true;
                             else {
                                  retval = false;
              return retval;
         }

  • SSIS Connection String Expression

    Hi 
    The bellow Expression shows my connection string expression 
    @[User::foldername]+"\"+ @[User::filename]
    it giving error, here i am passing two variable one for folder path and another for filename
    why it is showing error , how will i place "\" in between folder path and file name 
    please help in this
    Regards
    Malli

    If its inside expressions then you need to escape \ as \\
    see
    http://msdn.microsoft.com/en-us/library/ms141001.aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Evaluating a String True/False with a Regular Expression

    I need to write a regular expression to make the following strings display the values of true/false:
    112 Elm Street True
    112 South Elm St. True
    112 S. Elm True
    Elm St. False
    South 112 Elm False
    Here's what I have so far:
    public class MethodOne
         public static void main (String args[])
              return street.matches (//d+//s+[A-Z]{1}[a-z][.]?//s{1}[A-Z]{1}[a-z]+[.]);
            String address1 = "112 Elm Address"
            String address2 = "112 South Elm St."
            String address3 = "112 S. Elm"
            String address4 = "Elm St."
            String address5 = "South 112 Elm"
            if (address1.matches(street) ) {
            System.out.println("True");
            else {
            System.out.println("False")
               }// end if
         Can anyone help me out?

    Is this what you want?
    String address1 = "112 Elm Street";
    String address2 = "112 South Elm St.";
    String address3 = "112 S. Elm";
    String address4 = "Elm St.";
    String address5 = "South 112 Elm";
    String matchString = "\\d+ [A-Z,a-z,. ]+";
    System.out.println(address1.matches(matchString));
    System.out.println(address2.matches(matchString));
    System.out.println(address3.matches(matchString));
    System.out.println(address4.matches(matchString));
    System.out.println(address5.matches(matchString));

  • Issues with evaluation of EL expressions

    Hey everyone
    I am having issues with EL expressions being printed instead of evaluated when they are between tags. They work fine when they are in the tag itself. I will show you my code:
    This is a snippet from the parent file that includes the other file:
    <jsp:include page="./includes/test.jsp" >
      <jsp:param name="color" value="blue" />
    </jsp:include>This is the test.jsp file. It all works as expected except for that second line which only prints ${param.color} instead of the actual parameter text:
    REGULAR OUTPUT WORKS
    <br><font color="red"> COLOR OUTPUT WORKS</font>
    <br>${param.color}
    <br>Param inside color tag: <font color='${param.color}'>HERE</font>
    <% String test = request.getParameter("color"); %>
    <br>OUT.PRINT input: <% out.print(test); %>This is the output:
    REGULAR OUTPUT WORKS
    COLOR OUTPUT WORKS (this is in red)
    ${param.color}
    Param inside color tag: HERE (the word 'here' is in blue)
    OUT.PRINT input: blue
    In my book (Head First Servlets and JSP) it uses this exact syntax and says it should work. I am running tomcat 5.5. Any ideas? Thanks!
    John
    EDIT: I got it working with <c:out> but is there a way to do it without <c:out>?? Like I said before my book does it without <c:out> and it seems to work for them and is much cleaner looking that way.
    John
    Edited by: jrock on Nov 14, 2007 3:45 AM

    is there a difference between the JAR files for 1.0 and 1.1? Or is it the same JAR and only URI changes? Yes there is a difference between the 1.0 and 1.1 JSTL jar files.
    The JSTL1.1 jar files includes the JSTL1.0 tlds for backwards compatibility.
    Check what version you've got by looking at the Manifest.mf in the META-INF directory of one of the jars.
    You can get JSTL1.1 from here: http://jakarta.apache.org/site/downloads/downloads_taglibs-standard.cgi
    Also with JSP 2.0 / JSTL 1.1 is it possible to still use web.xml entries if I want? Its possible to retain those web.xml entries, but not really recommended. The container should find it without your spelling it out.
    If you do go down that path, just make sure you match the right URI to the right tld. Nothing would be more confusing than using the JSTL1.1 uri and mapping it to the JSTL1.0 tld file :-)
    Also, the <taglib> tags are no longer a top level element of a webapp, but need to be nested inside a <jsp-config> in the new schema.
    ie previously it was
    <web-app>
      <taglib>
        <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
        <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
      </taglib>
    ...The web.xml from from version 2.3 to 2.4 is not entirely compatible.
    You now need to make it
    <web-app>
    <jsp-config>
      <taglib>
        <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
        <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
      </taglib>
    </jsp-config>
    ...

  • Custom evaluation of EL expressions - extend ExpressionEvaluator?

    I have a model class (corresponding to a database table) with some exclusion flags, where the flags indicated that a field should not be displayed on a page where we choose to apply exclusions. For example, a person may request that their username and date of birth not be listed in a directory search, yet we would still want to show the username/birthdate on a page where the user is looking at their own information. For example:
    public class Person {
        private String name;
        private Date birthDate;
        private String username;
        private boolean excludeBirthDate;
        private boolean excludeUsername;
        // getters and setters
    }I want to write a tag such that I can say in my JSP:
    <page:applyExclusions>
        ${person.username} ${person.name} ${person.birthDate}
    </page:applyExclusions>and have only the person's name display (if they have requested that the other fields be excluded).
    Looking at the tags API, it seems like I would want to have my own ExpressionEvaluator whose evaluate method says something like
    public Object evaluate(String expr, Class type, VariableResolver resolver, FunctionMapper mapper) {
        if (type.equals(Person.class) &&
             expr.equals(someExcludedField)) {
             // return empty String or something to say "don't display the actual value"
        else {
            // ok to display value, evaluate like normal
            return super.evaluate(expr, type, resolver, mapper);
    }Not sure if I'm on the right track with my idea or if there's a better way to accomplish this?

    An expression evaluator is exactly that - searches for some variables in scope and performs evaluation on them according to a set of rules.
    IMO you shouldnt be changing this functionality to include your business logic there. You should be writing your own custom tags for such pruposes, something like
    <myTag:applyExclusions username="${userName}" name="${name}" birthDate="${brithDate}/>And in your tag code, you would have
    public int doEndTag() throws JspException {
            try {
                pageContext.getOut().println("UserName "+ userName);
                if(user is viewing the page)//your logic here{
                     pageContext.getOut().println("Name "+ name);
                     pageContext.getOut().println("Birth Date "+ birthDate);
            } catch (IOException exp) {
                throw new JspException(exp);
            return EVAL_PAGE;
    }  where userName, name and birthDate are attribute properties of the tag with get and set methods as evnafets suggested.
    Hope that helps.
    cheers,
    ram.

  • Evaluating an XML expression within from within an XML node

    I would like to pass in an E4X expression from a node and
    evaluate that expression.
    For example, let's say the XML looks like this:
    quote:
    <section id="a">
    <item id="1">
    <value>3.1</value>
    </item>
    <item id="2">
    <value>2.2</value>
    </item>
    <item id="3">
    <value
    calculated="true">{section.(@id=="a").item.(@id=="1").value +
    section.(@id=="a").item.(@id=="1").value}</value>
    </item>
    </section>
    I would then like to evaluate this from within Flex,
    displaying each of the values from the three items and evaluating
    the expression that lies in the third item.
    Note: this doesn't work... (but it's the idea... that is, to
    retrieve the expression from the XML and evaluate it)...
    quote:
    <mx:Script>
    <![CDATA[
    [Bindable]
    public var xmlHUD:XML;
    ]]>
    </mx:Script>
    <mx:Label
    text="{myXML.section.item.(@id=='3').value}"/>
    If successful, the label would then display the result from
    the express in item 3, which would be 5.3 (the result of 3.1 +
    2.2).
    Any ideas?
    David

    Your prayer is answered! :)
    Check out the DAS.eval() Library; it is designed just for
    this purpose. You can pass in a string of any AS3 expression
    (including E4X) and even algorithms and get a value back. Check it
    out at
    Adobe | Communities | Exchange | Flex | Libraries
    or simply go to
    http://www.flexisco.com/daseval/
    Cheers!
    - Ann

  • Evaluating binary strings with "Don't care" conditions

    I frequently have to evaluate binary strings or register values for particular bits. Does anyone have a better way? And if not, perhaps this is a suggestion for NI.
    To this point I've used two methods:
    1. I turn the data into an actual string in my CVI code and inject X's in the necessary positions. I then perform a string evaluation for equivalence, the string now consisting of '1's '0's and 'x's.
    2. Bring the data into the teststep and applying an expression to the data source, masking the appropriate bits. Then evaluate as a numeric with a value that assumes the offended bits "zeroness" or "oneness" depending on how I've implemented.
    The first was one requires specialized code, but allows for a little more visibility (in the code at least) of which bits are designated as DCs. But translating a multiple byte and variable length of amount of information into a string is cumbersome. Sure the code is reusable, but I'm not convinced the translation is necessary or best.
    The second buries the mask in a window that is, seemingly, infrequently used. I've had colleagues work on a project behind me trying to figure out where the value was being manipulated because I've applied a mask via the source. My original explanation of "ninjas" wasn't well taken...
    It seems like it would be ideal for the limits window to allow the use of "X"s when defining a "binary" type comparison so that the mask is clearly defined in the limit itself, and the data as it's passed to and from teststand remains untouched. Also, if this were to be implemented I would hope the property loader would support it.
    Am I missing a much easier way to do this? Anyone have a better way?
    Thanks in advance!
    Colt.
    P.S. Why isn't "NI" and "CVI" built into the spell checker?

    So in that first case where I am using CVI to "insert" I am building a string type vector that contains ASCII '1's '0's and 'x's. Where the Xs are in the binary position for what I am considering as "don't care".
    So say for instance I was converting a piece of data that was 0xEB, with bit 0 being considered a DC for evaluation, I would build a string like "1110 101X" . This string is what I would pass back to teststand. In teststand I would then perform an equivalence test between the two strings.
    For the second question about an implementation for the limit, say I open the test step, click on "Edit Limits" then from the drop down in the bottom right I select "Binary". I could then compose a limit in a similar form as described above. Where the limit box could contain something like "0b1110101X". But as for the data I hand to teststand, it would still be just a scalar value, with no masks applied. In the code, or in teststand.
    Sorry if I'm not making any sense! I hardly ever do...
    Colt.

  • Evaluation of EL Expression having Logical AND

    Consider the below EL code as an example
    #{model1.valA and model2.valB}
    I have the following questions related to this:
    1. Will the model2.valB get evaluated if model1.valA returns false?
    2. When exactly does the expression get evaluated in the servlet lifecycle?
    thanks.

    I assume model1 and model2 are beans, since they are not implicit objects. As you said, I am also assuming both return boolean.
    So, you should expect:
    ${true and true} to return true
    ${true and false} to return false
    ${false and false} to return false
    So, the answer to your question 1 is yes.
    2) _jspService();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Evaluating a el expression in output text

    Is there a way I can split the value :  #{node.DepatmentName} of the af:outputText component on the client side ? The requirement is to split the string on "-" and return the first part. Trying to get this working from customization in app composer.

    hi,
    if u can, try it in sql .like this way pl/sql:
    this is sample -
    Select Nvl(Trim(Substr(trim('A-B'),1,(Instr(trim('A-B'),'-')-1))),'-') 
    from dual
    or if not nvl ,then put this eg: 
                      Select Substr(trim('A-B'),1,(Instr(trim('A-B'),'-')-1))  from dual ;
    thks.

  • Evaluating a String to XML element

    we had a xquery function
    getProductRepo($columnSelect as xs:int) as ns0:productVal
    for $productval in ns11:getProductVal()
    return
    <ns0:ProductVal>
    <repo1>fn:data($productval/val)</repo1>
    <repo2>fn:data($productval/val)</repo2>
    <repo3>fn:data($productval/val)</repo3>
    for $columnSelect in ns12:ColumnSelect()/module
    let $columnVal=$columnSelect[$columnSelect]/column
    <optionalElem?>fn:data($productval/$columnVal)</optionalElem>
    </ns0:ProductVal>
    in <optionalElem> we are expecting value is fn:data($productval/TotalProducts) ie "Arial".But we are getting TotalProducts ie the value of $columnVal.
    is any method in xquery/xpath to evaluate a string to element name.
    like eval().

    Can you please post a clear description of your problem? I have no idea why you expect $productval/TotalProducts to be "Arial".
    XQuery functions and operators can be found at
    http://www.w3.org/TR/xpath-functions/
    Are you looking for something like node-name( node ) ?

  • How to find length of a string in JSF using EL expressions.

    I am doing it as below for finding string length
    <c:set var="test" value="#{myPageBean.myMethod.length()}" />
    While evaluating the above expression,it will call getMyMethod() which will return a String. On that it will call length().
    But it this throwing parsing error,
    Is it different in JSF?..Pls help.

    BabuKhan wrote:
    I have imported the taglib in th below 3 ways and tried
    1. <anyxmlelement xmlns:fn="http://java.sun.com/jsp/jstl/functions" />
    2. <anyxmlelement xmlns:fn="http://java.sun.com/jstl/functions" />
    3. <anyxmlelement xmlns:fn="http://java.sun.com/jsf/functions" />
    Literally? Do you understand the meaning of "anyxmlelement" ?

  • Computing an expression in a string?

    I have an expression in a string, how can I compute this? I know I can put it in post fix and travers it with a Stack, but there must be an easier way in Java, e.g. How can I evaluation this string into an integer of 10?
    String s = "5+5";
    // how can I compute the expression in s???
    int i=???

    I appreciate the response, but have to agree with jschell
    With Java being an interpreted language, you would think it could resolve expressions built on the fly and residing in a string. I also see IDEs like IntelliJ that have an evaluate option in the debugger, so that is why I thought there might be a way. Perhaps they coded their own. I also saw a reference to an Expression Object, but could not make sense of it.
    If this issue of evaluatiing expressions in strings is a question has ben asked man times before, hopefully someone from Sun who works on the JDK is reading this, and considering adding this feature. I have seen this capability in another programming language, and have even seen the dynamic creation of programming statements built in strings.

  • Evaluating expression

    Hey there guys!!! i just have a simple problem, but this may be hard to find in java. Do java have an eval method where in it can evaluate expression like the one in JavaScript Math.eval("3+2*12"), for example?
    Or does anyone has a better (shorter and complete) way of implementing such method? thanks a lot!!! hope you can help me with that one guys. :-) thanks again and have a nice computing time! :-)

    You can try JFormula :
    http://www.japisoft.com/formula/
    Here the features :
    * Decimal, string, boolean operators (or, and, not, xor...)
    * Unicode
    * Boolean expression support : (A<B)&&(B>C), (A or B) and not ( C equals D )
    * String expression support : "abc" != "cba"
    * IF THEN ELSE expression
    * Short expression format : 2x+3y
    * Variable : A=(cos(PI + x )*2) + [y-x]^2
    * Multiple lines expression : A = 1 B = A + 1 ...
    * High precision mode
    * Functions with decimal, boolean or string arguments
    * Evaluation tree produced by a pluggable parsing system
    * Evaluation optimization for symbol value changes
    * Standard library with 24 mathematical functions
    * Delegate for resolving unknown functions or symbols
    * Extend or add a new library dynamically
    * Share multiple formula context
    * Override any functions from the current library by your one
    * Support for multithreaded computing
    * Many samples (library extension, graphes) for API interesting parts
    * JDK 1.1 compliant (tested on JDK1.1.8 and JDK1.4.2)
    Best regards,
    A.Brillant

Maybe you are looking for