Regular expression- insert into a string phrase "new" into correct position

I have sample data in table T below, and i have sample output how i want the query to output over that data.
with T as
select 'CREATE OR REPLACE PACKAGE BODY "YYY"."PACKAGEONE" IS' s from dual union all
select 'Create or REPLACE PACKAGE BODY "ZZZ"."PACKAGETWO" IS' s from dual
select REGEXP_REPLACE(T.s, '^.PACKAGE BODY$','(\1)_new',1,1,'i') as s from T;
Expected output:
CREATE OR REPLACE PACKAGE BODY "YYY"."PACKAGEONE_new" IS
Create OR REPLACE PACKAGE BODY "ZZZ"."PACKAGETWO_new" IS
*/All data has following pattern:
CREATE OR REPLACE PACKAGE BODY "[owner]"."[name]" ISWhere [owner] can be any string. In sample data we have for example values XXX and YYY there.
And [name] can be any string. In sample data we have for example values PACKAGEONE and PACKAGETWO there.
Other parts of the string is fixed and stays as you see.
As shown in expected output query should replace substring "[owner]"."[name]" to "[owner]"."[name]_new"
How can i write such query?
I think i somehow should in regular expression count the positions of double quotes to achieve the expected result, but i don't know how.

Thx, but your solution doesn't work, it doesn't put phrase "new" into string. I use Oracle 10g.
with T as
select 'CREATE OR REPLACE PACKAGE BODY "YYY"."PACKAGEONE" IS...' s from dual union all
select '...Create or REPLACE PACKAGE BODY "ZZZ"."PACKAGETWO" ..."a"."b" procedure a IS..' s from dual
select
RegExp_Replace(s,'(" IS$)','_new\1') as new
from t;
CREATE OR REPLACE PACKAGE BODY "YYY"."PACKAGEONE" IS...
...Create or REPLACE PACKAGE BODY "ZZZ"."PACKAGETWO" ..."a"."b" procedure a IS..
{code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • How to write regular expression to find desired string piece *duplicate*

    Hi All,
    Suppose that i have following string piece:
    name:ali#lastname:kemal#name:mehmet#lastname:cemalI need
    ali
    mehmetI use following statement
    SQL> select lst, regexp_replace(lst,'(name:)(.*)(lastname)(.*)','\2',1,1) nm from (
      2    select 'name:ali#lastname:kemal#name:mehmet#lastname:cemal' as lst from dual
      3  );
    LST                                                NM
    name:ali#lastname:kemal#name:mehmet#lastname:cemal ali#lastname:kemal#name:mehmet#
    SQL> But it does not return names correctly. When i change 5th parameter(occurence) of regexp_replace built-in function(e.g. 1,2), i may get ali and mehmet respectiveley.
    Any ideas about regexp?
    Note : I can use PL/SQL instr/substr for this manner; but i do not want to use them. I need regexp.
    Regards...
    Mennan
    Edited by: mennan on Jul 4, 2010 9:53 PM
    thread was posted twice due to chrome refresfment. Please ignore the thread and reply to How to write regular expression to find desired string piece

    The approach is to do cartesian join to a 'number' table returning number of records equal to number of names in the string.I have hardcoded 2 but you can use regexp_count to get the number of occurrences of the pattern in the string and then use level <=regexp_count(..... .
    See below for the approach
    with cte as(
    select
    'name:ali#lastname:kemal#name:mehmet#lastname:cemal' col ,level lev
    from dual connect by level <=2)
    select substr(regexp_substr('#'||col,'#name:\w+',1,lev),7)
    from cte
    /

  • Regular expression - parse version number string

    Hi,
    I try to parse a string using regular expressions but id did not work correctly in all cases.
    The string that i want to parse can have one of the following layout:
    3.4.5.v20090305 or
    3.4.5The first three parts have to be integer values, the last part can be a free string (which is optional).
    I use the following code to parse the version number and extract the parts:
    Pattern versionPattern = Pattern.compile("(\\d+)\\.{1}(\\d+)\\.{1}(\\d+)(?:\\.{1}(\\w+))?");
    Matcher m = versionPattern.matcher(versionString);
    if (!m.find()) {
        throw new IllegalArgumentException("Version must be in form <major>.<minor>.<micro>.<qualifier>");
    // assert that we matched every part
    // three groups (without qualifier) or four parts (with qualifier)
    int groups = m.groupCount();
    if (groups != 4) {
         throw new IllegalArgumentException("Version must be in form <major>.<minor>.<micro>.<qualifier>");
    // extract the parts
    major = parseInt(m.group(1));
    minor = parseInt(m.group(2));
    micro = parseInt(m.group(3));
    qualifier = m.group(4);The above regular expression works in all cases that i tested, except one.
    The follwoing string is accepted as correct input: (but it shouldn't)
    3.4.5a.v20090305And i get the result:
    major = 3
    minor = 4
    micro = 5
    qualifier = a.v20090305
    Thanks for help or suggestions :)
    Best Regards,
    Michael

    heissm wrote:
    Hi,
    I try to parse a string using regular expressions but id did not work correctly in all cases.
    The string that i want to parse can have one of the following layout:
    3.4.5.v20090305 or
    3.4.5The first three parts have to be integer values, the last part can be a free string (which is optional).
    I use the following code to parse the version number and extract the parts:
    Pattern versionPattern = Pattern.compile("(\\d+)\\.{1}(\\d+)\\.{1}(\\d+)(?:\\.{1}(\\w+))?");
    Matcher m = versionPattern.matcher(versionString);
    if (!m.find()) {
    throw new IllegalArgumentException("Version must be in form <major>.<minor>.<micro>.<qualifier>");
    // assert that we matched every part
    // three groups (without qualifier) or four parts (with qualifier)
    int groups = m.groupCount();
    if (groups != 4) {
    throw new IllegalArgumentException("Version must be in form <major>.<minor>.<micro>.<qualifier>");
    // extract the parts
    major = parseInt(m.group(1));
    minor = parseInt(m.group(2));
    micro = parseInt(m.group(3));
    qualifier = m.group(4);The above regular expression works in all cases that i tested, except one.
    The follwoing string is accepted as correct input: (but it shouldn't)
    3.4.5a.v20090305And i get the result:
    major = 3
    minor = 4
    micro = 5
    qualifier = a.v20090305No, that can't be the output. Perhaps you have some old class files you're executing, because with the code you now posted, that can't be the result.
    To verify this, execute this:
    import java.util.regex.*;
    public class Main {
        public static void main(String[] args) {
            String versionString = "3.4.5a.v20090305";
            Pattern versionPattern = Pattern.compile("(\\d+)\\.{1}(\\d+)\\.{1}(\\d+)(?:\\.{1}(\\w+))?");
            Matcher m = versionPattern.matcher(versionString);
            if (!m.find()) {
                throw new IllegalArgumentException("Version must be in form <major>.<minor>.<micro>.<qualifier>");
            // assert that we matched every part
            // three groups (without qualifier) or four parts (with qualifier)
            int groups = m.groupCount();
            if (groups != 4) {
                 throw new IllegalArgumentException("Version must be in form <major>.<minor>.<micro>.<qualifier>");
            // extract the parts
            System.out.println("1 -> "+m.group(1));
            System.out.println("2 -> "+m.group(2));
            System.out.println("3 -> "+m.group(3));
            System.out.println("4 -> "+m.group(4));
    }and you'll see that the following is the result:
    1 -> 3
    2 -> 4
    3 -> 5
    4 -> nullSome remarks about your pattern:
    "(\\d+)\\.{1}(\\d+)\\.{1}(\\d+)(?:\\.{1}(\\w+))?"All the "{1}" can be omitted they don't add anything to your regex and are only cluttering it up. And you'll probably also want to "anchor" your regex using the start- and end-of-string-meta-characters, like this:
    "^(\\d+)\\.(\\d+)\\.(\\d+)(?:\\.(\\w+))?$"

  • Regular expression for middle of string

    Bit of background. I'm getting both text (can contain numbers) and data (only numbers) from serial. Since I don't know which I'm receiving and when it starts/ends, I'm making the sender send "textSTART###textSTOP" where "###" is what I want to extract. ### can contain text, numbers, new line, carrige return or whatever.
    The same for data&colon; "dataSTART###dataSTOP", where ### contains only numbers.
    I think I should use Match Pattern, but I don't know how to make my regular expression.
    Any help is appreciated. 
    Solved!
    Go to Solution.

    If the string does not contain anything outside these "delimiters" and there are exactly two per string, you could simply use scan strings for tokens. You can also add the "dataSTART/STOP"  delimiters to the array to make it universal and look at the beginning of the raw string to determine if you are dealing with a "data" or "text" message.
    Here's a quick draft.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    TaggedText.png ‏10 KB

  • Regular Expression for Match Pattern (string) Function

    I need to find a variable length string enclosed by brackets and
    within a string. Can't seem to get the regular expression right for
    the Match Pattern function. I'm able to get the job done using the
    Token function, but it's not as slick or tight as I'd like. Does
    anybody out there have the expression for this?

    Jean-Pierre Drolet wrote in message news:<[email protected]>...
    > The regular expression is "\[[~\]]*\]" which means:
    > look for a bracket "\[" (\ is the escape char)
    > followed by a string not containing a closing bracket "[~\]]*"
    > followed by a closing bracket "\]". The match string include the
    > brackets
    >
    > You can also read "Scan from String" with the following format:
    > "%[^\[]\[%[^\[\]]" and read the 2nd output. The brackets are removed
    > from the scanned string.
    Thanks, Jean_Pierre
    I did some more experimenting after posting and found that \[.*\] also
    works with the match pattern function. Thanks for your input.
    sm

  • Regular Expressions and Numbers in Strings

    Looking for someone who has had experience in using Regular Expressions in the Classification Rule Builder.
    We have an eVar that is collecting the number of search results in this fashion:
    <Total Results>_<# of Item 1>_<# of Item 2>_<# of Item 3>_<# of Item 4>
    Example output would look like this:
    150_50_0_25_75
    What we've done is initially create a Regular Expression that looks like this:
    ^(.+)\_(.+)\_(.+)\_(.+)\_(.+)$
    The problem is, it appears in situations where the output contains a zero in one of the slots, the value is ignored and it receives the value in the next place over.  Using the example output shown above, I would end up with values like this:
    $0 150_50_0_25_75
    $1 150
    $2 50
    $3 25
    $4 75
    $5 {null}
    Here's the weird part.  When I perform a test of a single record, it appears like it will work just fine, but when it actually runs in Omniture, it's not working as expected.  Here's something else I'd like to know if it's possible to address.  The five-place string is only the newest iteration of this approach.  In the past, we started out with a two-place version, then three-place and then four.  Any recommendations for handling all scenarios?
    Any and all advice is welcome.  Thanks in advance!

    Doing some playing around on rubular.com and thinking the Regular Expression should be build this way instead:
    ^(\d+)\_(\d+)\_(\d+)\_(\d+)\_(\d+)$
    Again, still looking for any additional guidance from more experienced individuals.  Thanks!

  • Regular expressions: the shorter the string, the longer the time to analyse

    Hello there !
    I've got a problem with regular expressions...
    I analyse those two strings with the same regular expression, searching for the "message" word.
    The first of them, which is much longer than the other one, is instantly analysed... but the second one takes about to one second !
    Do you see the problem ? (I do not, as you can guess...).
    I tried to put the same special characters in the two ones... but it still works slowly for the second one.
    This is instantly analysed:
    "Coucou----- Origin.a.l. .message -----From: clems= To: Cl�ment S=ent: Wednes=day, April 30, 2003 1:38 PMSubject: Fw: mail de test----- Original Message -----From: clemsTo: Cl�ment Sent: Wednesday, April 30, 2003 1:37 PMSubject: mail de testcoucou, ceci est un mail de t.e.s.t... !!!Clems.".matches("((.*\\W)*\\Q" + "message" + "\\E(\\W.*)*)")
    This takes about to one second:
    "This is a b message ubodyub.brHere s a href= http:www.tano.fr.fm the second linea.".matches("((.*\\W)*\\Q" + crit�reActuel.getLeMot(i).toLowerCase() + "\\E(\\W.*)*)")
    Pleaaase, help ;)
    Clement

    Well in fact everything seems to work... there was another problem...
    My regular expression seems to be wrong and the code too...
    I apologize... sorry for the waste of time.
    See you later :) for my next wrong problem ! :))
    Clement

  • How to write regular expression to find desired string piece

    Hi All,
    Suppose that i have following string piece:
    name:ali#lastname:kemal#name:mehmet#lastname:cemalI need
    ali
    mehmetI use following statement
    SQL> select lst, regexp_replace(lst,'(name:)(.*)(lastname)(.*)','\2',1,1) nm from (
      2    select 'name:ali#lastname:kemal#name:mehmet#lastname:cemal' as lst from dual
      3  );
    LST                                                NM
    name:ali#lastname:kemal#name:mehmet#lastname:cemal ali#lastname:kemal#name:mehmet#
    SQL> But it does not return names correctly. When i change 5th parameter(occurence) of regexp_replace built-in function(e.g. 1,2), i may get ali and mehmet respectiveley.
    Any ideas about regexp?
    Note : I can use PL/SQL instr/substr for this manner; but i do not want to use them. I need regexp.
    Regards...
    Mennan

    Hi, Mennan,
    You can nest REGEXP_SUBSTR withing REGEXP_REPLACE to get the n-th occurrence, like this:
    SELECT     lst
    ,      REGEXP_REPLACE ( REGEXP_SUBSTR ( lst
                                      , 'name:[^#]*#lastname'
                               , 1
                               , n
                     , 'name:(.*)#lastname'
                     , '\1'
                     )      AS nm If the pattern occurs fewer than n times, the expression above returns NULL.

  • Regular expression for Scan from String

    I am trying to pick out three numbers with pattern $number1:number2:number3# from a stream, for instance 8.559509#$-1.686432:-2.427051:-7.281153#$-6.160924​:-1.763356:
    So far, I use "Scan from String" with Format string "$%f:%f:%f #". However I don't know how to ignore/delete the items before $. Would you like to help me with that? Cheers

    You know that your sequence of numbers begins with the $ and ends with the #, so you can separate them into groups first, then separate each number out.
    Bill
    (Mid-Level minion.)
    My support system ensures that I don't look totally incompetent.
    Proud to say that I've progressed beyond knowing just enough to be dangerous. I now know enough to know that I have no clue about anything at all.

  • Regular expression not working for String.split()?

    hi, i have a String variable called 'table'.
    It has a bunch of chunks of data seperated by whitespace, whether it
    be spaces or carraige returns. Anyways, i want to split this up using
    the String.split function. i want to split it around whitespace.
    here is my code:
    String codes[] = table.split("\s");
    However, i'm getting back all nulls in the codes variable. What am i doing wrong?
    thanks

    split("\\s")\ is special both in Java String literals and in regex, so you need two of them.
    You'll probably also have to take an extra step it you don't want regex to stop at newlines. I forget the details, so check the docs.

  • Regular expression help please. (extractin​g a string subset between two markers)

    I haven't used regular expressions before, and I'm having trouble finding a regular expression to extract a string subset between two markers.
    The string;
    Header stuff I don't want
    Header stuff I don't want
    Header stuff I don't want
    Header stuff I don't want
    Header stuff I don't want
    Header stuff I don't want
    ERRORS 6
    Info I want line 1
    Info I want line 2
    Info I want line 3
    Info I want line 4
    Info I want line 5
    Info I want line 6
    END_ERRORS
    From the string above (this is read from a text file) I'm trying to extract the string subset between ERRORS 6 and END_ERRORS. The number of errors (6 in this case) can be any number 1 through 32, and the number of lines I want to extract will correspond with this number. I can supply this number from a calling VI if necessary.
    My current solution, which works but is not very elegant;
    (1) uses Match Regular Expression to the return the string after matching ERRORS 6
    (2) uses Match Regular Expression returning all characters before match END_ERRORS of the string returned by (1)
    Is there a way this can be accomplished using 1 Match Regular Expression? If so could anyone suggest how, together with an explanation of how the regular expression given works.
    Many thanks
    Alan
    Solved!
    Go to Solution.

    I used a character class to catch any word or whitespace characters.  Putting this inside parentheses makes a submatch that you can get by expanding the Match Regular Expression node.  The \d finds digits and the two *s repeat the previous term.  So, \d* will find the '6', as well as '123456'.
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice

  • Introduction to regular expressions ... last part.

    Continued from Introduction to regular expressions ... continued., here's the third and final part of my introduction to regular expressions. As always, if you find mistakes or have examples that you think could be solved through regular expressions, please post them.
    Having fun with regular expressions - Part 3
    In some cases, I may have to search for different values in the same column. If the searched values are fixed, I can use the logical OR operator or the IN clause, like in this example (using my brute force data generator from part 2):
    SELECT data
      FROM TABLE(regex_utils.gen_data('abcxyz012', 4))
    WHERE data IN ('abc', 'xyz', '012');There are of course some workarounds as presented in this asktom thread but for a quick solution, there's of course an alternative approach available. Remember the "|" pipe symbol as OR operator inside regular expressions? Take a look at this:
    SELECT data
      FROM TABLE(regex_utils.gen_data('abcxyz012', 4))
    WHERE REGEXP_LIKE(data, '^(abc|xyz|012)$')
    ;I can even use strings composed of values like 'abc, xyz ,  012' by simply using another regular expression to replace "," and spaces with the "|" pipe symbol. After reading part 1 and 2 that shouldn't be too hard, right? Here's my "thinking in regular expression": Replace every "," and 0 or more leading/trailing spaces.
    Ready to try your own solution?
    Does it look like this?
    SELECT data
      FROM TABLE(regex_utils.gen_data('abcxyz012', 4))
    WHERE REGEXP_LIKE(data, '^(' || REGEXP_REPLACE('abc, xyz ,  012', ' *, *', '|') || ')$')
    ;If I wouldn't use the "^" and "$" metacharacter, this SELECT would search for any occurence inside the data column, which could be useful if I wanted to combine LIKE and IN clause. Take a look at this example where I'm looking for 'abc%', 'xyz%' or '012%' and adding a case insensitive match parameter to it:
    SELECT data
      FROM TABLE(regex_utils.gen_data('abcxyz012', 4))
    WHERE REGEXP_LIKE(data, '^(abc|xyz|012)', 'i')
    ; An equivalent non regular expression solution would have to look like this, not mentioning other options with adding an extra "," and using the INSTR function:
    SELECT data
      FROM (SELECT data, LOWER(DATA) search
              FROM TABLE(regex_utils.gen_data('abcxyz012', 4))
    WHERE search LIKE 'abc%'
        OR search LIKE 'xyz%'
        OR search LIKE '012%'
    SELECT data
      FROM (SELECT data, SUBSTR(LOWER(DATA), 1, 3) search
              FROM TABLE(regex_utils.gen_data('abcxyz012', 4))
    WHERE search IN ('abc', 'xyz', '012')
    ;  I'll leave it to your imagination how a complete non regular example with 'abc, xyz ,  012' as search condition would look like.
    As mentioned in the first part, regular expressions are not very good at formatting, except for some selected examples, such as phone numbers, which in my demonstration, have different formats. Using regular expressions, I can change them to a uniform representation:
    WITH t AS (SELECT '123-4567' phone
                 FROM dual
                UNION
               SELECT '01 345678'
                 FROM dual
                UNION
               SELECT '7 87 8787'
                 FROM dual
    SELECT t.phone, REGEXP_REPLACE(REGEXP_REPLACE(phone, '[^0-9]'), '(.{3})(.*)', '(\1)-\2')
      FROM t
    ;First, all non digit characters are beeing filtered, afterwards the remaining string is put into a "(xxx)-xxxx" format, but not cutting off any phone numbers that have more than 7 digits. Using such a conversion could also be used to check the validity of entered data, and updating the value with a uniform format afterwards.
    Thinking about it, why not use regular expressions to check other values about their formats? How about an IP4 address? I'll do this step by step, using 127.0.0.1 as the final test case.
    First I want to make sure, that each of the 4 parts of an IP address remains in the range between 0-255. Regular expressions are good at string matching but they don't allow any numeric comparisons. What valid strings do I have to take into consideration?
    Single digit values: 0-9
    Double digit values: 00-99
    Triple digit values: 000-199, 200-255 (this one will be the trickiest part)
    So far, I will have to use the "|" pipe operator to match all of the allowed combinations. I'll use my brute force generator to check if my solution works for a single value:
    SELECT data
      FROM TABLE(regex_utils.gen_data('0123456789', 3))
    WHERE REGEXP_LIKE(data, '^(25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})$') 
    ; More than 255 records? Leading zeros are allowed, but checking on all the records, there's no value above 255. First step accomplished. The second part is to make sure, that there are 4 such values, delimited by a "." dot. So I have to check for 0-255 plus a dot 3 times and then check for another 0-255 value. Doesn't sound to complicated, does it?
    Using first my brute force generator, I'll check if I've missed any possible combination:
    SELECT data
      FROM TABLE(regex_utils.gen_data('03.', 15))
    WHERE REGEXP_LIKE(data,
                       '^((25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})$'
    ;  Looks good to me. Let's check on some sample data:
    WITH t AS (SELECT '127.0.0.1' ip
                 FROM dual
                UNION 
               SELECT '256.128.64.32'
                 FROM dual            
    SELECT t.ip
      FROM t WHERE REGEXP_LIKE(t.ip,
                       '^((25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})$'
    ;  No surprises here. I can take this example a bit further and try to format valid addresses to a uniform representation, as shown in the phone number example. My goal is to display every ip address in the "xxx.xxx.xxx.xxx" format, using leading zeros for 2 and 1 digit values.
    Regular expressions don't have any format models like for example the TO_CHAR function, so how could this be achieved? Thinking in regular expressions, I first have to find a way to make sure, that each single number is at least three digits wide. Using my example, this could look like this:
    WITH t AS (SELECT '127.0.0.1' ip
                 FROM dual
    SELECT t.ip, REGEXP_REPLACE(t.ip, '([0-9]+)(\.?)', '00\1\2')
      FROM t
    ;  Look at this: leading zeros. However, that first value "00127" doesn't look to good, does it? If you thought about using a second regular expression function to remove any excess zeros, you're absolutely right. Just take the past examples and think in regular expressions. Did you come up with something like this?
    WITH t AS (SELECT '127.0.0.1' ip
                 FROM dual
    SELECT t.ip, REGEXP_REPLACE(REGEXP_REPLACE(t.ip, '([0-9]+)(\.?)', '00\1\2'),
                                '[0-9]*([0-9]{3})(\.?)', '\1\2'
      FROM t
    ;  Think about the possibilities: Now you can sort a table with unformatted IP addresses, if that is a requirement in your application or you find other values where you can use that "trick".
    Since I'm on checking INET (internet) type of values, let's do some more, for example an e-mail address. I'll keep it simple and will only check on the
    "[email protected]", "[email protected]" and "[email protected]" format, where x represents an alphanumeric character. If you want, you can look up the corresponding RFC definition and try to build your own regular expression for that one.
    Now back to this one: At least one alphanumeric character followed by an "@" at sign which is followed by at least one alphanumeric character followed by a "." dot and exactly 3 more alphanumeric characters or 2 more characters followed by a "." dot and another 2 characters. This should be an easy one, right? Use some sample e-mail addresses and my brute force generator, you should be able to verify your solution.
    Here's mine:
    SELECT data
      FROM TABLE(regex_utils.gen_data('a1@.', 9))
    WHERE REGEXP_LIKE(data, '^[[:alnum:]]+@[[:alnum:]]+(\.[[:alnum:]]{3,4}|(\.[[:alnum:]]{2}){2})$', 'i'); Checking on valid domains, in my opinion, should be done in a second function, to keep the checks by itself simple, but that's probably a discussion about readability and taste.
    How about checking a valid URL? I can reuse some parts of the e-mail example and only have to decide what type of URLs I want, for example "http://", "https://" and "ftp://", any subdomain and a "/" after the domain. Using the case insensitive match parameter, this shouldn't take too long, and I can use this thread's URL as a test value. But take a minute to figure that one out for yourself.
    Does it look like this?
    WITH t AS (SELECT 'Introduction to regular expressions ... last part. URL
                 FROM dual
                UNION
               SELECT 'http://x/'
                 FROM dual
    SELECT t.URL
      FROM t
    WHERE REGEXP_LIKE(t.URL, '^(https*|ftp)://(.+\.)*[[:alnum:]]+(\.[[:alnum:]]{3,4}|(\.[[:alnum:]]{2}){2})/', 'i')
    Update: Improvements in 10g2
    All of you, who are using 10g2 or XE (which includes some of 10g2 features) may want to take a look at several improvements in this version. First of all, there are new, perl influenced meta characters.
    Rewriting my example from the first lesson, the WHERE clause would look like this:
    WHERE NOT REGEXP_LIKE(t.col1, '^\d+$')Or my example with searching decimal numbers:
    '^(\.\d+|\d+(\.\d*)?)$'Saves some space, doesn't it? However, this will only work in 10g2 and future releases.
    Some of those meta characters even include non matching lists, for example "\S" is equivalent to "[^ ]", so my example in the second part could be changed to:
    SELECT NVL(LENGTH(REGEXP_REPLACE('Having fun with regular expressions', '\S')), 0)
      FROM dual
      ;Other meta characters support search patterns in strings with newline characters. Just take a look at the link I've included.
    Another interesting meta character is "?" non-greedy. In 10g2, "?" not only means 0 or 1 occurrence, it means also the first occurrence. Let me illustrate with a simple example:
    SELECT REGEXP_SUBSTR('Having fun with regular expressions', '^.* +')
      FROM dual
      ;This is old style, "greedy" search pattern, returning everything until the last space.
    SELECT REGEXP_SUBSTR('Having fun with regular expressions', '^.* +?')
      FROM dual
      ;In 10g2, you'd get only "Having " because of the non-greedy search operation. Simulating that behavior in 10g1, I'd have to change the pattern to this:
    SELECT REGEXP_SUBSTR('Having fun with regular expressions', '^[^ ]+ +')
      FROM dual
      ;Another new option is the "x" match parameter. It's purpose is to ignore whitespaces in the searched string. This would prove useful in ignoring trailing/leading spaces for example. Checking on unsigned integers with leading/trailing spaces would look like this:
    SELECT REGEXP_SUBSTR(' 123 ', '^[0-9]+$', 1, 1, 'x')
      FROM dual
      ;However, I've to be careful. "x" would also allow " 1 2 3 " to qualify as valid string.
    I hope you enjoyed reading this introduction and hope you'll have some fun with using regular expressions.
    C.
    Fixed some typos ...
    Message was edited by:
    cd
    Included 10g2 features
    Message was edited by:
    cd

    Can I write this condition with only one reg expr in Oracle (regexp_substr in my example)?I meant to use only regexp_substr in select clause and without regexp_like in where clause.
    but for better understanding what I'd like to get
    next example:
    a have strings of two blocks separated by space.
    in the first block 5 symbols of [01] in the second block 3 symbols of [01].
    In the first block it is optional to meet one (!), in the second block it is optional to meet one (>).
    The idea is to find such strings with only one reg expr using regexp_substr in the select clause, so if the string does not satisfy requirments should be passed out null in the result set.
    with t as (select '10(!)010 10(>)1' num from dual union all
    select '1112(!)0 111' from dual union all --incorrect because of '2'
    select '(!)10010 011' from dual union all
    select '10010(!) 101' from dual union all
    select '10010 100(>)' from dual union all
    select '13001 110' from dual union all -- incorrect because of '3'
    select '100!01 100' from dual union all --incorrect because of ! without (!)
    select '100(!)1(!)1 101' from dual union all -- incorrect because of two occurencies of (!)
    select '1001(!)10 101' from dual union all --incorrect because of length of block1=6
    select '1001(!)10 1011' from dual union all) --incorrect because of length of block2=4
    select '10110 1(>)11(>)0' from dual union all)--incorrect because of two occurencies of (>)
    select '1001(>)1 11(!)0' from dual)--incorrect because (!) and (>) are met not in their blocks
    --end of test data

  • Regular Expressions in ABAP

    Hi, all!
    Are there any possibilities to make use of regular expressions in 4.6C (FMs, classes)?
    Regards,
    Maxim.

    Hi Maxim and all others whoever may read this ,
    try the following code - but be patient and leave my (c) where it is:::
    You may also have a look at the specialities of JavaScipt RegEx.
    Yours,
    Johannes
    * an Example Call:
    DATA return_value TYPE string.
    DATA: match type ztmatch,
    lastindex TYPE i,
    leftcontext TYPE string,
    rightcontext TYPE string,
    index TYPE i,
    searchstring TYPE string,
    modifier TYPE string,
    regex TYPE string,
    found TYPE boolean,
           error_message type string.
    regex = 'b+(a)*(b+)'.
    searchstring = 'abbbbabbaa'.
    modifier = ''.
    CALL METHOD ztr_bw_tools=>regex
      IMPORTING
        LASTINDEX     = lastindex
        LEFTCONTEXT   = leftcontext
        RIGHTCONTEXT  = rightcontext
        INDEX         = index
        FOUND         = found
        MATCH         = match
        RETURN_VALUE  = return_value
        ERROR_MESSAGE = error_message
      CHANGING
        SEARCHSTRING  = searchstring
        MODIFIER      = modifier
        REGEX         = regex
    Changing SEARCHSTRING TYPE STRING  DEFAULT '' "string to be regex applicated
    Changing MODIFIER TYPE STRING  DEFAULT '' "/gims/
    Changing REGEX TYPE STRING  DEFAULT '' "regular expression
    Exporting LASTINDEX TYPE I
    Exporting LEFTCONTEXT TYPE STRING
    Exporting RIGHTCONTEXT TYPE STRING
    Exporting INDEX TYPE I
    Exporting FOUND TYPE BOOLEAN "boolean variable (X=true, -=false, space=unknown)
    Exporting MATCH TYPE ZTMATCH "For use with regular expressions
    Exporting RETURN_VALUE TYPE STRING
    Exporting ERROR_MESSAGE TYPE STRING
    method REGEX .
    * (c) by Johannes Rumpf - 2006 -
    * Matching-Table of part matches of brackets
    *DATA: BEGIN OF ztmatch,
    *        comp TYPE string,
    *      END OF ztmatch.
    DATA source TYPE string.
    DATA js_processor TYPE REF TO cl_java_script.
    js_processor = cl_java_script=>create( ).
    * JavaScript --> ABAP variablen Mapping
    js_processor->bind( EXPORTING name_obj  = ' '
                                  name_prop = 'regex'
                         CHANGING data      = regex ).
    js_processor->bind( EXPORTING name_obj  = ' '
                                  name_prop = 'searchstring'
                         CHANGING data      = searchstring ).
    js_processor->bind( EXPORTING name_obj  = ' '
                                  name_prop = 'modifier'
                         CHANGING data      = modifier ).
    js_processor->bind( EXPORTING name_obj  = ' '
                                  name_prop = 'index'
                        CHANGING  data      = index ).
    js_processor->bind( EXPORTING name_obj  = 'abap'
                                  name_prop = 'match'
                        CHANGING  data      = match ).
    js_processor->bind( EXPORTING name_obj  = ' '
                                  name_prop = 'lastindex'
                        CHANGING  data      = lastindex ).
    js_processor->bind( EXPORTING name_obj  = ' '
                                  name_prop = 'leftcontext'
                        CHANGING  data      = leftcontext ).
    js_processor->bind( EXPORTING name_obj  = ' '
                                  name_prop = 'rightcontext'
                        CHANGING  data      = rightcontext ).
    js_processor->bind( EXPORTING name_obj  = ' '
                                  name_prop = 'found'
                         CHANGING data      = found ).
    * eine Leerzeile hinzufügen
    DATA: wa like line of match.
    wa-comp = ' '.
    append wa to match.
    * JavaScript Code *REGEX*
    CONCATENATE
    'var re = new RegExp(regex, modifier);'
    'var m = re.exec(searchstring);'
    '  if (m == null) {'
    '    found = false;'
    '  } else {'
    '  found = true; '
    '    index = m.index;'
    '    lastindex = m.lastIndex;'
    '    leftcontext = m.leftContext;'
    '    rightcontext = m.righContext;   '
    '    var len = abap.match.length;'
    '    for (i = 0; i < m.length; i++) {'
    '      abap.match[len-1].comp = m<i>;'
    '      abap.match.appendLine();'
    '      len++;'
    INTO source SEPARATED BY cl_abap_char_utilities=>cr_lf.
    return_value = js_processor->evaluate( source ).
    error_message = js_processor->LAST_ERROR_MESSAGE.
    endmethod.

  • PrintWriter issue with Directory Traversal and Regular Expression

    This is a follow up to my previous question on the forum. I am developing a program traverses the hard drive for information. If it finds the said information in any of the file (based on the regular expression wriiten) it must print the output into the file. Currently I am able to traverse the harddrive perfectly, the regular expression and the search is perfect and when I print the output into the local console, I am able to derive perfect results. But when I use the PrintWriter to write the output into the flight, it writes NOTHING into the file. I have been scouring all over the Internet for an answer, but havent been able to find. Would highly appreciate if someone can tell me what I am doing wrong and provide some guidance on how to get it right.
    public class myClass{
        BufferedReader br;
        String pcv;
        Pattern scPattern = Pattern.compile("Some regular expression");
        Matcher match = null;
        Pattern newPattern = Pattern.compile("Some regular expression");
        Matcher newMatch = null;
        String mvCheckVal;
        Matcher mvMatch;
        PrintWriter pw;
        void recursiveMethod(File dir) throws Exception {
                pw = new PrintWriter(new FileWriter("outputFile.txt"));
                pw.println("Opening pw stream.....");
                File[] files = dir.listFiles();
                String[] fileList = dir.list();
                for (int i = 0;i < files.length; i++) {
                    if (files.isDirectory()) {
    continue;
    } else if (files[i].isFile()) {
    br = new BufferedReader(new FileReader(files[i]));
    pw.println("BR is opening....");
    String line;
    while((line = br.readLine()) != null) {
    match = scPattern.matcher(line);
    if (match.find()) {
    pcv = line.substring(match.start(), match.end());
    System.out.println("Match: " + pcv + " Context: " + match.replaceFirst(pcv)); //This is working perfectly
    pw.println("Match: " + pcv + " Context: " + match.replaceFirst(pcv)); //This does not print anything at all
    System.out.println("Files: " + files[i]);
    System.out.println("");
    pw.println(" Files: " + files[i]);
    pw.println("");
    System.out.println("Closing I/O....");
    br.close();
    pw.close();
    public static void main(String[]args) throws Exception {
    File dir = new File("C:/");
    myNewClass acf = new myNewClass();
    acf.myClass(dir);

    @ejp
    I am afraid that it is not working. Can you please tell me what I doing wrong.
    void myMethod(File dir) throws Exception {
                bw = new BufferedWriter(new FileWriter("outputFile.txt"));
                File[] files = dir.listFiles();
                String[] fileList = dir.list();
                for (int i = 0;i < files.length; i++) {
                    if (files.isDirectory()) {
    myMethod(files[i]);
    } else if (files[i].isFile()) {
    br = new BufferedReader(new FileReader(files[i]));
    String line;
    while((line = br.readLine()) != null) {
    match = scPattern.matcher(line);
    if (match.find()) {
    pcv = line.substring(match.start(), match.end());
    System.out.println("Match: " + pcv + " Context: " + match.replaceFirst(pcv));
    bw.write("Match: " + pcv + " Context: " + match.replaceFirst(pcv));
    br.close();
    bw.write("Files: " + files[i]);
    bw.write("");
    bw.close();
    public static void main(String[]args) throws Exception {
    File dir = new File("C:/");
    myClass acf = new myClass();
    acf.myMethod(dir);

  • How to find sunstring with regular expression?

    How can I find a substring in a string with a regular expression?
    Example:
    I have a original string "<tr><th>RecordId: </th><td valign=middle>A4711</td></tr>"
    Now i want to extract the value "A4711" from this string with a regular expression. Everything except "A4711" is fixed, the id "A4711" itself is dynamic. How is it possible to get the substring "A4711" of the original string with a regular expression?

    i wrote a little method with the infos above to get such results:
         * Get all substrings of a string that matches a regular expression.
         * @param original String to inspect.
         * @param regExp Regular expression as search criteria.
         * @return All matches of <i>regExp</i> or null if one input parameter is null.
        public static String[] getSubstrings(String original, String regExp) {
            String[] result = null;
            if (original != null && regExp != null) {
                Pattern pattern = Pattern.compile(regExp);
                Matcher matcher = pattern.matcher(original);
                boolean matchFound = matcher.find();
                Vector matches = new Vector();
                while (matchFound) {
                    String match = matcher.group();        
                    matches.addElement(match);
                    matchFound = matcher.find();
                }//next match
                int count = matches.size();
                result = new String[count];
                for (int i = 0; i < count; i++) {
                    result[i] = (String) matches.elementAt(i);
                }//next match
            }//else: input unavailable
            return result;
        }//getSubstrings()

Maybe you are looking for

  • How do I get iTunes Help to work?  (v 11)

    After entering a term in Help - search, it provides a list of Help Topics that do nothing when clicked. 

  • Downloaded iTunes but Windows cannot open file

    I am on my shiny new Toshiba notebook and I cannot open the iTunes program I just downloaded. When I try to open and run it I get a Windows message that it needs to know what program created it. How do I open a .pf file? I never had this problem on m

  • How to read .doc files on 5800 express music? pls ...

    When I try and open my .doc files it says file format error or something... Recently installed Office on my phone... New to this... please help...

  • EE customer

    Okay, where to begin. I'll start with the absolute rubbish we've been told by BT, that our connection isn't capable of running any faster than it already is. We moved over from BT to Orange (now EE), as it just worked out cheaper as the account holde

  • Rental won't stop downloading

    Rented a movie on my iPad, watched it (well, 90%), and the 24 hour rental period is well past.  Want to rent another movie, but even though aforementioned movie rental has been deleted (manually by me) from the "videos" app, it still shows up in iTun