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);
}

Similar Messages

  • 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.

  • Query help in regular expression

    Hi all,
    SELECT * FROM emp11
    WHERE INSTR(ENAME,'A',1,2) >0;
    Please let me know the equivalent query using regular expressions.
    i have tried this after going through oracle regular expressions documentation.
    SELECT * FROM emp11
    WHERE regexp_LIKE(ename,'A{2}')
    Any help in this regard would be highly appreciated .
       Thanks,
    P Prakash

    please go here
    Introduction to regular expressions ...
    Thanks,
    P Prakash

  • Help with regular expression to find a pattern in clob

    can someone help me writing a regular expression to query a clob that containts xml type data?
    query to find multiple occurrences of a variable string (i.e <EMPID-XX> - XX can be any number). If <EMPID-01> appears twice in the clob i want the result as EMPID-01,2 and if EMPID-02 appears 4 times i want the result as EMPID-02,4.

    with
    ofx_clob as
    (select q'~
    <EMPID>1
    < UNQID>123456
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>2
    < UNQID>123457
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>1
    < UNQID>123458
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    ~' ofx from dual
    select '<EMPID>' || to_char(ids) || '(' || to_char(count(*)) || ')' multi_empid
      from (select replace(regexp_substr(ofx,'<EMPID>\d*',1,level),'<EMPID>') ids
              from ofx_clob
            connect by level <= regexp_count(ofx,'<EMPID>')
    group by ids having count(*) > 1
    MULTI_EMPID
    <EMPID>1(2)
    with
    ofx_clob as
    (select q'~
    <EMPID>1
    < UNQID>123456
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>2
    < UNQID>123457
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>1
    < UNQID>123456
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>2
    < UNQID>123456
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>1
    < UNQID>123458
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    ~' ofx from dual
    select '<EMPID>' || listagg(to_char(ids) || '(' || to_char(count(*)) || ')',',') within group (order by ids) multi_empid
      from (select replace(regexp_substr(ofx,'<EMPID>\d*',1,level),'<EMPID>') ids
              from ofx_clob
            connect by level <= regexp_count(ofx,'<EMPID>')
    group by ids having count(*) > 1
    MULTI_EMPID
    <EMPID>1(3),2(2)
    Regards
    Etbin
    Message was edited by: Etbin
    used listagg to report more than one multiple <EMPID>

  • Help in regular expression matching

    I have three expressions like
    1) [(y2009)(y2011)]
    2) [(y2008M5)(y2011M3)] or [(y2009M5)(y2010M12)]
    3) [(y2009M1d20)(y2011M12d31)]
    i want regular expression pattern for the above three expressions
    I am using :
    REGEXP_LIKE(timedomainexpression, '???[:digit:]{4}*[:digit:]{1,2}???[:digit:]{4}*[:digit:]{1,2}??', 'i');
    but its giving results for all above expressions while i want different expression for each.
    i hav used * after [:digit:]{4}, when i am using ? or . then its giving no results. Please help in this situation ASAP.
    Thanks

    I dont get your question Can you post your desired output? and also give some sample data.
    Please consider the following when you post a question.
    1. New features keep coming in every oracle version so please provide Your Oracle DB Version to get the best possible answer.
    You can use the following query and do a copy past of the output.
    select * from v$version 2. This forum has a very good Search Feature. Please use that before posting your question. Because for most of the questions
    that are asked the answer is already there.
    3. We dont know your DB structure or How your Data is. So you need to let us know. The best way would be to give some sample data like this.
    I have the following table called sales
    with sales
    as
          select 1 sales_id, 1 prod_id, 1001 inv_num, 120 qty from dual
          union all
          select 2 sales_id, 1 prod_id, 1002 inv_num, 25 qty from dual
    select *
      from sales 4. Rather than telling what you want in words its more easier when you give your expected output.
    For example in the above sales table, I want to know the total quantity and number of invoice for each product.
    The output should look like this
    Prod_id   sum_qty   count_inv
    1         145       2 5. When ever you get an error message post the entire error message. With the Error Number, The message and the Line number.
    6. Next thing is a very important thing to remember. Please post only well formatted code. Unformatted code is very hard to read.
    Your code format gets lost when you post it in the Oracle Forum. So in order to preserve it you need to
    use the {noformat}{noformat} tags.
    The usage of the tag is like this.
    <place your code here>\
    7. If you are posting a *Performance Related Question*. Please read
       {thread:id=501834} and {thread:id=863295}.
       Following those guide will be very helpful.
    8. Please keep in mind that this is a public forum. Here No question is URGENT.
       So use of words like *URGENT* or *ASAP* (As Soon As Possible) are considered to be rude.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need help with regular expression

    I'm trying to use the java.util.regex package to extract URLs from html files.
    The URLs that I am interested in extracting from the HTML look like the following:
    <font color="#008000">http://forum.java.sun.com -
    So, the URL is always preceeded by:
    <font color="#008000">
    and then followed by a space character and then a hyphen character. I want to be able to put all these URLs in a Vector object. This doesn't seem like it should be too difficult but for some reason I can't get anywhere with it. Any help would be greatly appreciated. Thanks!

    hi gupta am not sure of the java syntax but i can tell u about the regular expression...try this....
    <font color="#008000">(http:\/\/[a-zA-Z0-9.]+) [-]
    i dont know the java methods to call...just the reg exp...
    Sanjay Acharya

  • Help on regular expression

    hi all
    i need to validate telephone number , and i tried to use the following expression :
    "[\\d][\\d][\\d]-[\\d][\\d][\\d][\\d]" or
    "[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]" they did not seem to work. can anyone provide some help on this? thanks in advance.

    Hi,
    Can anyone provide me the regular expression for the following?
    1. String Should contain 7 letters (can include '*') followed by 5 alphanumeric characters i.e.5 numbers/letters
    For this one, I've written reg expn = ([a-zA-Z]*[*]*[a-zA-Z]*){7}\\w{5}
    But, somehow this is not working...can anyone pleaseeeee explain wots wrong with this one or give me alternate solution???????
    2. String should contain 7 numbers or 7 digits consisting of 1 letter & 6 numbers in varying order, no spaces.
    For this one, reg expn = (\\d{7})|((\\d*[a-zA-Z]\\d*){7})
    But this is also not working...... Please help!!!!!
    3. String should contain 9 numbers or 8 alphanumeric characters i.e. 8 numbers/letters or 13 numbers
    This one looks really simple, but still (\\d{9})|(\\w{8})|(\\d{13}) is not working.....Please helpppp
    I'll appreciate if any Regular Expresion expert can resolve my problem!!! Also, I'm using gnu-regexp-1.0.8.jar as we r not using JDK 1.4!!!! We've to use only this library, no other choice...so, please suggest!!!!!!

  • Help with Regular Expression for field validation

    I'm fairly new to using regular expressions and using Acrobat. This is probably a simple question, but I've been unable to figure it out.
    I have a text field on a PDF that I would like to be 9 characters in length. The first 2 characters can only be alphanumeric, the last 7 characters can only be numeric.
    At first I was using the following, which allows all the characters to be alphanumeric:
    var re = /^[A-Za-z0-9 :\\_]$/;
    if (event.change.length >0) {
    if (event.willCommit == false) {
        if (!re.test(event.change)) {
            event.rc = false
    That works fine, but it's not quite what I needed. With some assistance I changed it (see below) to fit what I was looking for. However, this didn't work; it prevents anything from being entered in the field:
    var re = /^[A-Za-z0-9]{2}\d{7}$/;
    if (event.change.length >0) {
    if (event.willCommit == false) {
        if (!re.test(event.change)) {
            event.rc = false
    Any help would be greatly appreciated.
    Thanks...

    Here's a function you can call form the field's custom Format script. It should be placed in a document-level JavaScript:
    function custom_ks1() {
        // Define non-commited regular expression
        var re = /^[A-Za-z0-9]{0,2}([0-9]{0,7})?$/;
        // Get all of the characters the user has entered
        var value = AFMergeChange(event);
        // Allow field to be cleared
        if(!value) return;
        if (event.willCommit) {
            // Define commited regular expression
            var re = /^[A-Za-z0-9]{2}[0-9]{7}$/;
            if (!re.test(value)) {  // If final value doesn't match, alert user
                app.alert("Your error message goes here.");
                // event.rc = false
        } else {  // not commited
            // Only allow characters that match the regular expression
            event.rc = re.test(value);
    Call it like this:
    // Custom Keystroke script
    custom1_ks();

  • Help with regular expression needed

    Hi,
    Perhaps someone here can help me with my regular expression I'm trying to build in my Java code.
    The regular expression that I'm looking to build consists of any non-whitespace character up until it finds one or two <>= symbols and then any character thereafter. So both these Strings would match the expression:
    City 1==London
    Age>=18
    The regular expression that I'm using is as follows:
    (\\S+)([><=]){1,2}(.+)However, group 1 always retrieves the first <>= symbol as in "City 1=". How can I make the <>= part greedy so that it retrieves both operator symbols?
    Thanks.

    Make the first group, the non-spaces, reluctant:
    "(\\S+?)([<>=]{1,2})(.+)"

  • Help With Regular Expression In Apex Validation

    Apex 3.2
    There is a validation type of regular expression in apex, but I have never used regular expression before,
    so a little help is appreciated.
    I need to validate a field. It is only allowed to contain alpha characers, numbers, spaces and the - (dash) character.
    I have tried several times to get this working
    eg
    [[:alpha:]]*[[:digit:]]*[[:space:]]*[-]*
    ^[[:alpha:][:digit:][:space:]-]+?
    and others, but just can't to get the syntax correct.
    Can someone help me with this please
    Gus

    Example:
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 'This is some example text' as txt from dual union all
      2             select 'And this is the 2nd one with numbers' from dual union all
      3             select 'And this allows double-barrelled words with hyphens' from dual union all
      4             select 'But this one shouldn''t be allowed!' from dual
      5            )
      6  --
      7  select *
      8  from t
      9* where regexp_like(txt, '^[[:alnum:] -]*$')
    SQL> /
    TXT
    This is some example text
    And this is the 2nd one with numbers
    And this allows double-barrelled words with hyphens

  • Help with Regular Expressions and regexp_replace

    Oh great Oracle Guru can I can gets some help
    I need to clean up the phone numbers that have been entered in Oracle eBusiness per_phones table. Some of the phone numbers have dashes, some have spaces and some have char. I would just like to take all the digits out and then re-format the number.
    Ex.
    914-123-1234 .. output (914) 123-1234
    9141231234 ..again (914) 123-1234
    914 123 1234 .. (914) 123-1234
    myphone ... just null
    (914)-123-1234.. (914) 123-1234
    I really tried to understand the regular expressions statments, but for some reason I just can't understand it.

    Hi,
    Welcome to the forum!
    I would create a user-defined function for this. I expect there will be a lot of exceptions to the regular rules (for example, strings that do not contain exactly 10 digits, such as '1-800-987-6543') that can be handled, but would require lots of nested fucntions and othwer complicted code if you had to do it in a single statement.
    If you really want to do it with a regular expression:
    SELECT     phone_txt
    ,     REGEXP_REPLACE ( phone_txt
                     , '^\D*'          || -- 0 or more non-digits at the beginning of the string
                           '(\d\d\d)'     || -- \1 = 3 consecutive digits
                    '\D*'          || -- 0 or more non-digits
                           '(\d\d\d)'     || -- \2 = 3 consecutive digits
                    '\D*'          || -- 0 or more non-digits
                           '(\d\d\d)'     || -- \3 = 4 consecutive digits
                    '\D*$'             -- 0 or more non-digits at the end of the string
                     , '(\1) \2-\3'
                     )          AS new_phone_txt
    FROM    table_x
    ;

  • Help on regular expressions

    im learning about regular expressions and im i want to write a regular expression to split the string like this:
    comp_complex=9
    comp_medium=5
    comp_simple=2
    and store it in an array...but even after trying various combinations im unable to split it...i dont know how to start..please help.....
    [{comp_complex=9, comp_medium=5, comp_simple=2, comp_id=111}, {comp_complex=0, comp_medium=5, comp_simple=0, comp_id=112}, {comp_complex=15, comp_medium=10, comp_simple=5, comp_id=113}, {comp_complex=14, comp_medium=7, comp_simple=2, comp_id=114}, {comp_complex=17, comp_medium=12, comp_simple=5, comp_id=115}, {comp_complex=15, comp_medium=8, comp_simple=3, comp_id=116}]

    I think I can guess -         String[] splitLine = line.replaceAll("[\\[\\]{}\\s]+","").split(",");
      

  • 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!

  • Help in Regular expression

    Hello..
    I wanted to write a regular expression to match the foll string..
    <!--endclickprintexclude--><!--startclickprintexclude--> <!--endclickprintexclude-->
    <p> <b>NEW ORLEANS, Louisiana (CNN) </b>
    -- Two years after Hurricane Katrina devastated coastal areas of Louisiana and Mississippi, residents say much of America has forgotten their plight.
    </p> <!--startclickprintexclude-->
    I tried doing..
    Matcher matcher= Pattern.compile("<!--endclickprintexclude--> <p><b>([^<^>]+?)</p><!--startclickprintexclude-->", Pattern.CASE_INSENSITIVE).matcher(story);
    Its not working...
    is there any other soln?

    Theres probably a better way to do this but here's a way that works.
    import java.util.regex.*;
    public class RegexTester{
    public static void main(String[] args){
         String text =
         "<!--endclickprintexclude--><!--startclickprintexclude--> <!--endclickprintexclude-->" +
         "<p> <b>NEW ORLEANS, Louisiana (CNN) </b>" +
         "-- Two years after Hurricane Katrina devastated coastal areas of Louisiana and Mississippi," +
         "residents say much of America has forgotten their plight." +
         "</p> <!--startclickprintexclude-->";
         String regex = ">((?:\\s*[\\S&&[^<>]]+\\s*)*?)<";
         Pattern p = Pattern.compile(regex);
         Matcher m = p.matcher(text);
         while(m.find()){
         System.out.println("Match: '" + m.group(1) + "'");
    }

  • Litte help with regular expression?

    Greetings all,
    I have a simple regular expression "(\\w+)\\s(\\w+)\\s(.+)"
    Which I want to match against the strings like "Acetobacter pasteurianus LMD22.1"
    But this always fails whenever there is a dot (.) character like "LMD22.1" in above string.
    How to solve this ?
    Thanks in advance.

    Shouldn't that be Acinetobacter?
    edit: nope, I'm wrong, you're right.
    Edited by: Encephalopathic on Apr 7, 2009 7:34 PM

Maybe you are looking for

  • HP Color LaserJet 1500L - drops off the 802.11n network

    My HP Color LaserJet 1500L drops off the network (it just stops printing). This happens when it is plugged into the usb bus of my new 802.11n base station or directly into the usb bus of a computer. The only way to fix it seems to be to plug it direc

  • How to create a clock with: a reset, start and stop

    How can i create a clock that have to do the following thing: Countdown visual in the screen Timeset with day's in seconds - Pressing start -> it start to run - Pressing stop -> The clock is stopping but it keeps the time, when i press start again th

  • Transfer documents b/w iPad and borrowed laptop

    I am travelling soon for work and can only take my iPad. I will need to transfer files between my iPad and a borrowed MacBook. Can I do this without transferring all of my data and apps?

  • R12: Multiple Tab Reports (Content Set)

    All, We are on R12 and we are using Report Manager and WebADI. In Report Manager if we run an FSG report with a content set it opens up in Excel, with one tab for each value in the content set. So, all is good. However, in core GL when we run Program

  • Microsoft Office documents cannot be selected for combination into a PDF.

    I have reinstalled Acrobat Pro XI twice.  Version of Office is 2010 32-bit.  See screenshot below.  Office documents are not available as supported at all.