Help needed regarding regular expressions

hello
i need to write a program that recieves a matematical expression and evaluates
it...in other words a calculator :)
i know i need to use regular expressions inorder to determine if the input is legal or not ,but i'm really having trouble setting the pattern
the expression can be in the form : Axxze2223+log(5)+(2*3)*(5+4)
where Axxze2223 is a variable(i.e a combination of letters and numbers.)
where as: l o g (5) or log() or Axxx33aaaa or () are illegal
i tried to set the pattern but i got exceptions or it just didnt work the way i wanted it .
here's what i tried to do at least for the varibale form:
"\\s*(*([a-zA-Z]+\\d)+)*\\s*";
i'm really new to this...and i can't seem to set the pattern by using regular expressions,how can i combine all the rules to one string?
any help or references would be appreciated
thanks

so i'll explain
let's say i got token "abc22c"(let's call it "token")
i wan't to check if it's legal
i define:
String varPattern = "\\s*[a-zA-Z]+\\d+\\s*";If you want to check a sequence of ASCII characters, longer than one, followed by a single digit, the whole possibly surrounded by spaces -- yes.
>
now i want to check if it's o.k
so i check:
token.matches(varPattern);
am i correct?Quite. It's better to compile the Pattern (Pattern.compile(String)), create a java.util.regex.Matcher (Pattern#matcher(CharSequence)), and test the Matcher for Matcher#matches().
(Class.method -> static method, Class#method -> instance method)
>
now i'm having problem defining pattern for log()
sin() cos()
that brackets are mandatory ,and there must be an
expression inside
how do i do that?First, I'd check the overall function syntax (a valid name, brackets), then whether what's inside the brackets is a valid expression (maybe empty), then whether that expression is valid for that function (presumably always?).
I might add I'm no expert on parsing, so that's more a supposition than a guide.

Similar Messages

  • Help needed in Regular Expression

    I have been give a task to replace all table_name (Emp) in Procedure p1 to Table_name(Employee).
    Can anyone help me ?
    Regards,
    Prathamesh

    Hi, Prathamesh,
    REGEXP_REPLACE ( txt
                , '(^|\W)emp(\W|$)'
                , \1employee\2'
                )will return a copy of txt with the full word 'emp' replaced by 'employee'.
    For example, if txt is:
    emp foo a=emp  temp emp_name emp.bthe expression above will return
    employee foo a=employee  temp emp_name employee.b 
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statments) and the results you want from that data.

  • Help needed on Regular expressions

    Hi All,
    I need to extract the value of the below 2 tags
    1. <S143:name> (main tag not the <S143:name> of <S143:specCharacteristicProperty>)
    2. <S110:stringValue>
    <S211:falloutCharacteristic>
                   *<S143:name>String</S143:name>*               <S143:value>
                        <S110:stringCharacteristicEnum>
                             *<S110:stringValue>String</S110:stringValue>*                         <S110:stringRestriction>
                                  <S110:minLength>0</S110:minLength>
                                  <S110:maxLength>0</S110:maxLength>
                                  <S110:pattern>String</S110:pattern>
                             </S110:stringRestriction>
                        </S110:stringCharacteristicEnum>
                   </S143:value>
                   <S143:description>String</S143:description>
                   <S143:specCharacteristicProperty>
                        <S143:name>String</S143:name>
                        <S143:value>String</S143:value>
                   </S143:specCharacteristicProperty>
              </S211:falloutCharacteristic>Any pointers on this?
    Thanks in advance.

    Well..Personally i feel regex on this would be a tough job. You try creating a temp file and pass your xml string along. Then try using org.w3c.dom on it. Something like :
    String xmlString = "Your XML String";
              File temp = null;
              try {
                   temp = File.createTempFile("test",".xml");
                   temp.deleteOnExit();
                   BufferedWriter out = new BufferedWriter(new FileWriter(temp));
                   out.write(xmlString);
                   out.close();
              } catch (IOException e) {
                   e.printStackTrace();
              }Or you could actually create a physical file, if space and credentials permit, access it from a physical location and try using DOM in it.. Cant think of anything better now.

  • Need a regular expression for the text field

    Hi ,
    I need a regular expression for a text filed.
    if the value is alphanumeric then min 3 char shud be there
    and if the value is numeric then no limit of chars in that field.[0-9].
    Any help is appriciated...
    thanks
    bharathi.

    Try the following in the change event:
    r=/^[a-z]{1,3}$|^\d+$/i;
    if (!r.test(xfa.event.newText))
    xfa.event.change="";
    Kyle

  • Help needed regarding Scanner class

    hello
    i'm really desperate for help, i'll mention that this is homework,but i need a small guidance.
    i need to code a calculator,we need to use the Scanner class to break the expression to tokens(we CANNOT use other classes).
    my main problem is about getting those tokens from the input string.
    i tried breaking a string to tokens for hours but just couldnt do it.
    a legal expression is something like:
    xyzavbx1111+log(abc11*(2+5))+sin(4.5)
    iilegal is : xx333aaaa111+2 or log()+2
    where the alphanumerics are variables(sequence of letters followed by numbers)
    i managed to get the tokens out of a string that looks like that:
    String expression = "ax11111+32/3+4*2^2"
    by doing:
    _token = new Scanner(expression);
    while(hasNext(_token)) getNextToken(_token,"\\d+(\\.\\d+)?|(\\+)|(\\-)|(\\*)|(\\/)|(\\^)|([a-zA-Z]+(\\d+));
    public static boolean hasNext(Scanner s) {
    return s.hasNext();
    public static String getNextToken(Scanner s,String str) {
    return s.findInLine(str);
    but i can't get the tokens when i have sin ,cos or log in the expression
    either it just ignores it or i'm looping infinitely.
    my question is how can i make the regular expression include the sin log and cos?
    I also know that when i'll use the "matches" method ,i'll be able to spot illegal arguments like 5//2+ because it doesnt match the pattern.
    so any help conecrning the regular expression would be great thanks alot.

    thx , but i already got it,after trying tons of combinations
    i'll post the format i used in case someone will find this thread in the future ,while looking for something similar
    the format is:
    "(\\s)|(log)|(sin)|(cos)|(\\d+(\\.\\d+)?)|(\\+)"+
    "|(\\-)|(\\*)|(\\/)|(\\^)|([a-zA-Z]+(\\d+))|(\\()|(\\))|(\\s)";
    which includes white spaces between arguments and operators

  • Query regarding Regular expressions

    Help me in regular expression for “one or two digits must followed by : and one or two digits”

    user8701050 wrote:
    thanqI assume you meant "thank you." Please use real words.
    In any case, you're welcome. So now that you know, your best course of action would be to study that tutorial, and/or this one: http://www.regular-expressions.info/tutorial.html, take your best shot, then post again if you get stuck, showing what you tried and explaining clearly the problems you encountered.
    Good luck!

  • Need help in unix regular expressions

    Hi All,
    I'm new to shell scripting. Please help me in achieving this
    I am trying to a find regular expression that need to pick a file with begin with the below format and mask variable is called in xml file.
    currently the script accepts:
    mask="CLIENT_ID+'_ADHSUITE_IN_'+date2str(now,'MMddyy','US/Eastern')+'.txt'"
    But it should accept in the below format
    2595_ADHSUITE_IN_ANNWEL_030309_2009-02-10_15-12-46-000_648.TXT715.outpgp_out
    where CLIENT_ID=2595. How to place wild card character '*' in the below to accept file in the above format. here is what i made changes.
    mask="CLIENT_ID+'_ADHSUITE_IN_'*+date2str(now,'MMddyy','US/Eastern')*+'.TXT'*+'.outpgp_out'"
    Please help.
    Thanks

    I believe your statement is being passed over twice:
    First Pass: (This is done by something like javascript)
    CLIENT_ID+'_ADHSUITE_IN_'+'.*'+date2str(now,'MMddyy','US/Eastern')+'.*'+'.TXT'+'.*'+'.outpgp_out'In this pass the variables and functions that are enclosed in literals are processed:
    (1) CLIENT_ID is replaced by 2595 or whatever is current value is:
    (2) date2str(now,'MMddyy','US/Eastern') gets replaced by 040609 (if the current time now is 4th april 2009).
    So at the end of this first pass we have a string:
    2595_ADHSUITE_IN_.\*040609.\*.TXT.*.outpgp_outThis string at the end of the first pass is a Posix basic regular expression. (ref: [http://en.wikipedia.org/wiki/Regular_expression] ) accessed at time of post).
    This is the string I put in the Regular Expression text box on [http://www.fileformat.info/tool/regex.htm]
    and it matches "2595_ADHSUITE_IN_ANNWEL_040609_2009-01-27_17-02-28-000_631.TXT715.outpgp_out" for me (though I prefer my egrep test).
    I hope this is somewhat clearer. Remember I have very little information about your system/application and I make big guesses.
    NB: (I should thank Frits earlier for pointing my sloppiness between wildcards (for eg unix shell filename expansion) and regular expressions).
    For the second pass this used to compared other strings to see

  • Help regarding regular expression

    HI All ,
    Please see the following string
    String s = "IF ((NOT NUM4 IS ALPHABETIC ) AND NUM3 IS ALPHABETIC-UPPER AND (NUM5 IS GREATER OR EQUAL TO 3) AND (NUM5 IS NOT GREATER THAN 3) AND (NUM3 GREATER THAN 46) AND (NUM5 GREATER THAN NUM3) OR NUM3 LESS THAN 78) .";
    My problem is: i want to capture the part of this line which contains "ALPHABETIC ,ALPHABETIC-UPPER for ex :NOT NUM4 IS ALPHABETIC , NUM3 IS ALPHABETIC-UPPER.from that I have to capture the word num4 , num3 which are in these phrases only ;from the whole string whereever it exists along with the phrase,Can any one help me out by suggesting something.num4 and num3 are variable names

    I suspect you're right, Sabre, but I can't resist...
    import java.util.regex.*;
    * A rewriter does a global substitution in the strings passed to its
    * 'rewrite' method. It uses the pattern supplied to its constructor, and is
    * like 'String.replaceAll' except for the fact that its replacement strings
    * are generated by invoking a method you write, rather than from another
    * string. This class is supposed to be equivalent to Ruby's 'gsub' when given
    * a block. This is the nicest syntax I've managed to come up with in Java so
    * far. It's not too bad, and might actually be preferable if you want to do
    * the same rewriting to a number of strings in the same method or class. See
    * the example 'main' for a sample of how to use this class.
    * @author Elliott Hughes
    public abstract class Rewriter
      private Pattern pattern;
      private Matcher matcher;
       * Constructs a rewriter using the given regular expression; the syntax is
       * the same as for 'Pattern.compile'.
      public Rewriter(String regularExpression)
        this.pattern = Pattern.compile(regularExpression);
       * Returns the input subsequence captured by the given group during the
       * previous match operation.
      public String group(int i)
        return matcher.group(i);
       * Overridden to compute a replacement for each match. Use the method
       * 'group' to access the captured groups.
      public abstract String replacement();
       * Returns the result of rewriting 'original' by invoking the method
       * 'replacement' for each match of the regular expression supplied to the
       * constructor.
      public String rewrite(CharSequence original)
        this.matcher = pattern.matcher(original);
        StringBuffer result = new StringBuffer(original.length());
        while (matcher.find())
          matcher.appendReplacement(result, "");
          result.append(replacement());
        matcher.appendTail(result);
        return result.toString();
      public static void main(String[] args)
        String s = "IF ((NOT NUM4 IS ALPHABETIC ) " +
                    "AND NUM3 IS ALPHABETIC-UPPER " +
                    "AND (NUM5 IS GREATER  OR EQUAL TO 3) " +
                    "AND (NUM5 IS NOT GREATER THAN 3) " +
                    "AND (NUM3 GREATER THAN 46) " +
                    "AND NUM645 IS ALPHABETIC " +
                    "AND (NUM5 GREATER THAN NUM3) " +
                    "OR NUM3 LESS THAN 78 " +
                    "AND NUM34 IS ALPHABETIC-UPPER " +
                    "AND NUM92 IS ALPHABETIC-LOWER " +
                    "AND NUM0987 IS ALPHABETIC-LOWER) .";
        String result =
          new Rewriter("(NUM\\d+) +IS +(ALPHABETIC(?:-(?:UPPER|LOWER))?)")
            public String replacement()
              String type = group(2);
              if (type.endsWith("UPPER"))
                return "Character.isUpper(" + group(1) + ")";
              else if (type.endsWith("LOWER"))
                return "Character.isLower(" + group(1) + ")";
              else
                return "Character.isLetter(" + group(1) + ")";
          }.rewrite(s);
        System.out.println(result);
    }

  • Need help in writing regular expressions involving \w

    Hi,
    Here is my requirement .
    I have a string : GTA - 12AB TRA - 12AB
    I need a regex that represent above string.
    GTA - Constant - This wont change
    12AB - This will be \w (alphanumeric)
    Here I cannot have TRA within this 4 characters.
    The question is :
    How can I write an expression which says it can be a word(the positions where I have 12AB in example) but not TRA in sequence.
    Is this doable?
    Thanks in advance.

    Use lookarounds: [http://www.regular-expressions.info/lookaround.html]
    The regex:
    (?!.?TRA).{4}matches any 4 characters (except line breaks) that does not contain 'TRA'.

  • Help with Understanding Regular Expressions

    Hello Folks,
    I need some help in understanding the Regular Expressions.
    -- This returns the Expected string from the Source String. ", Redwood Shores,"
    SELECT
      REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA,aa',
                    ',[^,]+,', 1, 1) "REGEXPR_SUBSTR"
      FROM DUAL;
    REGEXPR_SUBSTR
    , Redwood Shores,
    However, when the query is changed to find the Second Occurrence of the Pattern, it does not match any. IMV, it should return ", CA,"
    SELECT
      REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA,aa',
                    ',[^,]+,', 1, *2*) "REGEXPR_SUBSTR"
      FROM DUAL;
    REGEXPR_SUBSTR
    NULLCan somebody help me in understanding Why Second Query not returning ", CA,"?
    I did search this forum and found link to thread "https://forums.oracle.com/forums/thread.jspa?threadID=2400143" for basic tutorials.
    Regards,
    P.

    PurveshK wrote:
    Can somebody help me in understanding Why Second Query not returning ", CA,"?With your query...
    SELECT
      REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA,aa',
                    ',[^,]+,', 1, *2*) "REGEXPR_SUBSTR"
      FROM DUAL;You are looking for patterns of "comma followed by 1 or more non-comma chrs followed by a comma."
    So, let's manually pattern match that...
    '500 Oracle Parkway, Redwood Shores, CA,aa'
                       ^               ^
                       |               |
                               |
                               |
                      Here to here is the
                      first occurence.So the second occurance will start searching for the same pattern AFTER the first occurence.
    '500 Oracle Parkway, Redwood Shores, CA,aa'
                                        ^
                                        |
    i.e. the search for the second occurence starts heretherefore the first "," from that point is...
    '500 Oracle Parkway, Redwood Shores, CA,aa'
                                           ^
                                           |
                                          hereand there is nothing there matching the pattern you are looking for because it only has the
    "comma follwed by 1 or more non-comma chrs"... but it doesn't have the "followed by a comma"
    ...so there is no second occurence,

  • Help needed regarding the updation of "Relationships" in BP

    Hello Guys,
    This is to request you to kindly help me regarding the following.
    We have a scenario where all the employees assigned to an Organizational unit (in PPOMA_CRM) are not showing in the "Relationships" ("Has Employee")in the BP transaction of that Organizational Unit.
    Could anyone let me know whether there is any update program that updates the "Relationships" from the Organizational asssignment. Or we need to enter the employees manually in BP "Relationships". Please help. Thanks in anticipation.
    Regards,
    Kishore.

    Hi Amit,
    Thanks alot for your reply. Its really helpful for me.
    So,we usually enter these relationships manually only, right? Before going ahead with the custom program, could you please let me know whether there is any SAP note related to this.Once again thanks alot for you help.
    Regards,
    Kishore.

  • Help with java regular expressions

    Hi all ,
    i am going to match a patternstring against an input string and print the result here is my code:
         import java.util.regex.*;
         import java.util.*;
         public class Main {
              private static final String CASE_INSENSITIVE = null;
              public static void main(String[] args)
              CharSequence inputStr = "i have 5 years FMCG saLEs exp on java/j2ee and i worked on java and j2ee and 2 projects on telecom java j2ee domain with your  with saLEs maNAger experience of java j2ee and c# having very good  on c++ exposure in JAVA"
             String patternStr = "\"java j2ee\" and \"c#\"";
              StringTokenizer st = new StringTokenizer(patternStr,"\",OR");
             Matcher matcher=null;
              while(st.hasMoreTokens()){
                   String s=st.nextToken();
                   Pattern pattern = Pattern.compile(s,Pattern.CASE_INSENSITIVE);
               matcher = pattern.matcher(inputStr);
               while (matcher.find()) {
                  String result = matcher.group();
                 if(!result.equalsIgnoreCase(" "))
                             System.out.println("result:"+result);
         when i compile this code i am getting the expected result...ie
    result:java j2ee
    result:java j2ee
    result: and
    result: and
    result: and
    result: and
    result: and
    result: and
    result:c#
    but when i replace String patternStr = "\"java j2ee\" and \"c#\""; with
    String patternStr = "\"java j2ee\" and \"c++\""; i am just getting c in the result instead of c++ ie i am getting result :
    result:java j2ee
    result:java j2ee
    result: and
    result: and
    result: and
    result: and
    result: and
    result: and
    result:C
    result:c
    result:c
    result:c
    result:c
    result:c
    result:c
    In the last lines i should get result:c++ instead of result: c
    Any ideas please
    Thanks

    In the last lines i should get result:c++ instead of result: cThe regular expression parser considers the plus sign '+' a special
    character; it means: one or more times the previous regular expression.
    So 'c++' means one or more 'c's on or more times. Obviously you don't
    want that, you want a literal '+' plus sign. You can do that by prepending
    the '+' with a backslash '\'. Unfortunately, the javac compiler considers
    a backslash a special character and therefore you have to 'escape'
    the backslash also, by adding another backslash. The result looks
    like this:"c\\+\\+"kind regards,
    Jos

  • Help needed regarding replication in ds5.2sp4

    Hi ,
    I am new to ldap . I am able to establish replication between master and consumer and trying to update it is getting update but i am geting the following error
    in error log
    INFORMATION - NSMMReplicationPlugin - conn=-1 op=-1 msgId=-1 - Replication bind to consumer alpha.ad.com:19941 failed:
    [16/May/2007:13:48:26 -0700] - INFORMATION - NSMMReplicationPlugin - conn=-1 op=-1 msgId=-1 - Failed to connect to replication consumer alpha.ad.com:19941
    [16/May/2007:13:48:26 -0700] - ERROR<8318> - Repl. Transport - conn=-1 op=-1 msgId=-1 - [S] Bind failed with response: Failed to bind to remote (900).
    Please help me regarding this .
    Message was edited by:
    ap7926

    If data is getting replicated from master to consumer then the bind for that specific replication agreement is working.
    Check your timestamps and current log entries. Are the "Failed to connect to replication" messages currently being generated? As long as your replication agreement is enabled the supplier will try to keep things up and running, retrying a failed consumer regularly (and generating about 1 set of log messaages per minute on my systems). So you'll get those messages on the supplier when a good consumer is down (the nsslapd directory server process that is).
    If you don't have these messages being generated currently then this probably means that your consumer was down around "16/May/2007:13:48:26 -0700" but is ok now. In that case those messages aren't of big concern. They're just telling you that you had a problem, which you hopefully already knew about.
    If replication is working (test by making a change on the supplier and checking it on the consumer) AND you're still concurrently getting these messages regularly then you have something interesting going on, probably due to a configuration issue. Without seeing the details it's difficult say what it would be.

  • Need a regular expression for URL

    Regular expression: ^(udp|norm)://(?:(?:25[0-5]|2[0-4]\\d|[01]\\d\\d|\\d?\\d)(?(?=\\.?\\d)\\.)){4}:(6553[0-5]|655[0-2][0-9]\\d|65[0-4](\\d){2}|6[0-4](\\d){3}|[1-5](\\d){4}|[1-9](\\d){0,3})$
    Source: udp://125.3.4.121:23456
    Getting error:java.util.regex.PatternSyntaxException: Unknown inline modifier near index 54
    ^(udp|norm)://(?:(?:25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)(?(?=\.?\d)\.)){4}:(6553[0-5]|655[0-2][0-9]\d|65[0-4](\d){2}|6[0-4](\d){3}|[1-5](\d){4}|[1-9](\d){0,3})$

    paulcw wrote:
    I can't help wondering if a simpler solution would involve creating a java.net.URL object, passing it the string to be checked, and let URL do the parsing and an initial pass at checking the syntax. Then you could query URL for individual components for further checking (e.g., getting the transfer type to make sure it's one of the kinds you want). This approach would probably be more self-documenting, if nothing else.Nice idea, but java.net.URL doesn't actually do much work at all. It basically takes the protocol part, looks up a handler for it, and delegates everything else to that. The handlers themselves are down in the sun packages (or whatever your Java impl is) and since there isn't one for the OPs protocol, he'd have to write and register his own anyway, which kind-of negates the entire purpose of leveraging it.
    @OP: Paul's suggestion can still be of use. Apache, Codehaus and the like will have written their own protocol handlers, it's worth grabbing the source code for, say, Apache HttpClient, and seeing if they've got anything useful in there. Then again, who's to say that what's a valid URL for this 'norm' protocol, other than whoever designed the protocol?

  • Open APEX Wiki needs a regular expression mastermind

    Hello,
    And I'm not talking about someone that kinda knows regular expression's, we need one of those sick in the head people that think regular expressions are fun to do on a Friday night :) for some of this wiki work.
    If your interested please email me directly at [email protected]
    Sorry for putting this out here but I'm throwing a wide net on this one and want to kickstart this application.
    Carl

    [Heh, the "not built here", "we can build it better" approach, the bane (and boon!) of all software development]
    Seriously, I don't think Perl regexps are all that "non-standard" as compared to the POSIX standard. They certainly have some quirks w.r.t zero-length forward/backward assertions (?pattern) and they might have some more character classes [[:pattern:]] but on the whole it is the same stuff.
    Yes, given that TWiki is built entirely in Perl, it might have more than its fair share of "Perl-isms" that might make converting to Oracle regexps untenable, but there is no reason to use the TWiki "dialect" of wiki-markup. There are tons of Wiki dialects around, Google for keywords like "wiki dialect markup convert html" finds lots of relevant hits (like the link I posted earlier).
    All I am saying is that it might make sense to not reinvent the wheel especially for something as complicated as regular expressions.
    References:
    http://www.ayni.com/perldoc/perl5.8.0/pod/perlre.html
    http://builder.com.com/5100-6388-5224420.html
    http://www.oreilly.com/catalog/oracleregex/index.html
    http://www.redwingnet.com/hioug/Presentations/Regular_Expressions/Oracle10gRegularExpressions.htm

Maybe you are looking for

  • How to open and analysis the .gsf file extension file

    Hi friends Hi have .gsf file and i want to open in visual studio does anyone know this

  • How do you type multiple lines on a path? (label for top slope of bottle)

    Ill describe the best I can... I am making a label that will wrap around the top half of a bottle, the part that slopes to the spout.  Because of this, the label is actually shaped more like an arch so when it goes onto the bottle, it will look more

  • Connecting a touch screen monitor to Pavilion 17 e-137cl

    I'd like to use touch screen capability on when I have an exterior monitor connected with that capability (Acer T232HL).   It has Windows 8.1 updated but I cannot find a way to initiate pen and touch to the exterior monitor.  Is this possible?   This

  • Blinking templates

    I'm creating a site using templates. When I preview the site in Safari or Firefox, the site blinks every time navigating to a different page. - or actually in Safari it's only the swf animation, inserted in the header as my logo that blinks, the othe

  • Storing iStore purchases on iCloud

    I have purchased several HD films & programmes recently and my iTunes library which is on an external hard drive is getting very full I need to free up space on my external hard drive & wondered if I need to store them elsewhere ie iCloud, in order t