Padding numbers within a string

Hi Folks,
I have some strings which are all a mix of letters and numbers - no particular rules, but no special characters.
For ordering purposes, I would like to be able to lpad each number string to 5 digits (in reality there will never be more than 3 digits in a row)
For example:
XX01 -> XX00001
XX100 -> XX00100
XX1YY10ZZ1 ->XX00001YY00010ZZ00001
Any thoughts on how this can be achieved?
I am currently trying to get something working with REGEXP_REPLACE but cant quite get it working:
select pc.pcode,REGEXP_REPLACE(pc.pcode, '([[:digit:]]+)',lpad('\1',5,0))
from test_tab pc
order by 2
The actual/desired results are as follows:
ORIG DESIRED RESULT ACTUAL RESULT
=== =========== ==========
XX01 XX00001 XX00001 (correct)
XX10 XX00010 XX00010 (correct)
XX100 XX00100 XX000100 (incorrect)
XX1YY10ZZ1 XX00001YY00010ZZ00001 XX0001YY00010ZZ0001 (incorrect)
Thanks for any input you may have!
Matt
Edited by: Matthew Morgan on Jan 10, 2013 7:59 PM
Edited by: Matthew Morgan on Jan 10, 2013 7:59 PM
Edited by: Matthew Morgan on Jan 10, 2013 8:00 PM

Hi, Matt,
Matthew Morgan wrote:
... I am currently trying to get something working with REGEXP_REPLACE but cant quite get it working:
select pc.pcode,REGEXP_REPLACE(pc.pcode, '([[:digit:]]+)',lpad('\1',5,0))
from test_tab pc
order by 2
/In case you're wondering why that didn't work:
The arguments to REGEXP_REPLACE can be any kind of expressions of the right datatype. In particular, the 3rd argument is supposed to be a string, so it's perfectly okay to use a function that returns a string, such as
LPAD ('\1', 5, '0')in that place. (The 3rd argument to LPAD is supposed to be string. You passed a NUMBER instead, but Oracle implicitly converted that to a string for you, and no harm was done this time.)
When you pass an expression like that as an argument to REGEXP_REPLACE, the expression is evaluated first, and then it's results are passed back to REGEXP_REPLACE. What does
LPAD ('\1', 5, '0')evaluated to? It's the 5-character string:
000\1'\1' has no special meaning to LPAD; it's just a 2-character string. '\1' has special meaning in REGEXP_REPLACE, but this is not being done in the context of REGEXP_REPLACE, in fact, this has to be done before REGEXP_REPLACE can do its job. So, regardless of what's in pcode, what you wrote is equvalent to
select    pc.pcode
,       REGEXP_REPLACE ( pc.pcode
                   , '([[:digit:]]+)'
                   , '000\1'
from      test_tab pc
order by  2which adds exactly 3 0's before every number, regardless of how many digits are in that number. So when you happened to have 2-digit numbers (as in 'XX01') it happened to return the results you wanted.
chris227 wrote:
A more cautious version of frank solution could be to replace only the kind of digits added previously
SELECT       str
,       REGEXP_REPLACE ( REGEXP_REPLACE ( str
                                   , '(\d+)'
                           , '0000\1'
                   , '0+(\d{5})' --changed \d to 0
                   , '\1'
                   )     AS padded_str
FROM       str
ORDER BY  padded_str
Good idea!
Edited by: Frank Kulash on Jan 11, 2013 10:28 AM

Similar Messages

  • Separating character and number within the string

    I want to separate the character and the number within one string.
    For example,
    12345ABCD (the numbers and character may differ in lengths)
    I want to separate into two different string of 12435 and ABCD.
    Your help would be greatly appreciated.
    Thanks!

    here is an example:
    sample_separator.sql
    declare
      i        number := 0;
      j        number := 0;
      x        number := 0;
      vBasis   Varchar2(40) := '12345ABCD';
      vString1 Varchar2(40);
      vString2 Varchar2(40);
    begin
      for x in 1 .. length(vBasis) loop
        for i in 0 .. 9 loop
          if substr(vBasis,x,1) = to_char(i) then     
            vString1 := vString1 || substr(vBasis,x,1);
          end if;
        end loop;
        for j in 65 .. 90 loop
          if substr(vBasis,x,1) = chr(j) then
            vString2 := vString2 || substr(vBasis,x,1);
          end if;
        end loop;   
      end loop;
      dbms_output.put_line('vString1: '||vString1);
      dbms_output.put_line('vString2: '||vString2);
    end;
    /when run:
    SQL> @r:\sample_separator.sql;
    vString1: 12345
    vString2: ABCD
    PL/SQL procedure successfully completed.
    SQL> hope this helps.

  • Process Message failed: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.

    Hi
    I am trying to process an X12 message and I am getting following error.
    Method : ProcessMessage
    Message : Process Message failed: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
    Parameter name: length
       at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
       at Q.Inbound.X12Preprocessor.getTranTypeFromFuncCode()
       at Q.Inbound.X12Preprocessor.setProcessType()
       at Q.Inbound.X12Preprocessor.getFuncGroupHeader(StreamReader sr)
       at Q.Inbound.X12Preprocessor.ProcessMessage(X12Definition& docInfo)
    Please help.
    Thanks

    Might try them over here.
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=csharpgeneral%2Cvbgeneral%2Cvcgeneral&filter=alltypes&sort=lastpostdesc
    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows]
    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees , and confers no rights.

  • [JS - CS3]  Can't REPLACE A with B within a string? Help Please...

    Hello Experts,
    First off - I'm a newbee to all this JS and especially with CS3.
    I have a string: '
    b myDocumentName
    which can have it's value as: '
    b 00000en_ Generator WX/WY
    Problem is, backshlashes ( / )are a bad thing for me...
    b Question:
    How can I do a 'replace' operation to replace the '/' from the string with a '_'?
    I have at the moment:
    > var myDocSaveName = oneResult[3]+oneResult[4]+oneResult[5];
    > myDocSaveName.replace(what "/", with "");
    > myDoc.save ("C:/DATA/"+myDocSaveName, undefined, undefined, true)
    I get an error Nr. 25... Offending text:"/"
    What am I doing wrong?

    'what' and 'with' are the names of those arguments. They should not be included in the statement:
    myDocSaveName.replace("/", "");
    But that still won't work because replace doesn't operate on a string in situ, it returns the modified string. So:
    myDocSaveName = myDocSaveName.replace("/", "");
    This too has its limitations. It'll change only the first instance of "/", not all of them. To change all of them, you need to restate the 'what' as a RegExp:
    myDocSaveName = myDocSaveName.replace(/\//g, "_");
    A RegExp literal is delimited by the "/" character, so to have it, alone, as the character to be sought you must use the backslash to escape the character. Then, to indicate you want the replace to happen globally within the string, you add the 'g' after the RegExp.
    Dave

  • How to get a set of character within a string?

    Hi,
    I need to cut a set of character within a string. I have tried everthing but I need help.
    Example.
    Database Version 11.2.0.3
    create table tst_string (message varchar2(600));
    insert into tst_string values ('ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)');
    insert into  tst_string values ('ANE4175I Starting Full VM restore of VMware Virtual Machine ''mfujiwara'' target node name=''VC1_DC1'', data mover node name=''VC1_DC1_DM3''  (SESSION: 3780)');
    commit;
    select * from tst_string;
    MESSAGE
    ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)
    ANE4175I Starting Full VM restore of VMware Virtual Machine 'mfujiwara' target node name='VC1_DC1', data mover node name='VC1_DC1_DM3'  (SESSION: 3780)
    ## I want get
    # From first line following values:
    node OSOGBO
    filespace OSOGBO\SystemState
    examined 43
    deleted 43
    retrying 0
    failed 0
    # From second line
    mfujiwara
    VC1_DC1
    VC1_DC1_DM3Any help can be useful...
    Thanks in advance.

    Hi Frank,
    It looks like message can be seen as delimited lsit of sub-messages, where a number of different characters (perhaps ',' amd ':') may serve as delimiters. Each sub-message may or consist (entirely or in part) of something you want to display.Yes. In my first case where is "ANR0166I" I want get the characteres before "," (e.g "OSOGBO," I want get "OSOGBO") excluding "(SESSION: 1506, PROCESS: 2)"
    Would a user-define PL/SQL function be okay for you?Yes.. no problem.
    I'm not good with shell script, but will try show what I want using SHELL commands:
    See this example:
    ### I create a file named "tst_string"
    $ vi tst_string
    ANR0166I Inventory file expiration finished processing for node OSOGBO, filespace OSOGBO\SystemState\NULL\System State\SystemState, copygroup BACKUP and object type GROUP BASE with processing statistics: examined 43, deleted 43, retrying 0, and failed 0. (SESSION: 1506, PROCESS: 2)
    ## So I used a function sed to get my desired values. The command bellow is poor, but My point is the result.
    $ cat tst_string | sed 's/ANR0166I.*node //g' | sed 's/, filespace//g' | sed 's/, copygroup BACKUP and object type GROUP BASE with processing statistics: //g' | sed 's/. (SESSION.*//g' | sed 's/, deleted//g' | sed 's/, retrying//g' | sed 's/, and failed//g'
    OSOGBO OSOGBO\SystemState\NULL\System State\SystemState 43 43 0 0The result was:
    NODE     FILESPACE                              Examined     Deleted     Retrying        Failed      
    OSOGBO      OSOGBO\SystemState\NULL\System State\SystemState     43           43      0           0I will go check the links wich you mentioned.
    Thanks

  • Searching for numbers in a string

    I am trying to filter passwords stored in a string variable and ensure that they contain at least a number and one capital letter.
    how do you search for numbers in a string and search if that string contains a character in uppercase?

    function checkString(username){
    var userfield = username;
    var valid = '0123456789ABCDEFGHIJKLMN�OPQRSTUVWXYZ'; // define valid characters
    if(!isValid(userfield.value,valid)){
    alert("Invalid user name format");
    userfield.value="";
    userfield.select();
         userfield.focus();
    }else{
    err = 0;
    userfield = userfield.value;
    function isValid(string,allowed) {
    for (var i=0; i< string.length; i++) {
    if (allowed.indexOf(string.charAt(i)) == -1)
    return false;
    return true;
    }

  • Finding a word within a string

    Hey everyone,
    Just having a little trouble with something.
    I'm trying to find a word -- that is, not a substring, an actual word as defined by the english language -- within a string.
    For example I don't want "hell" to be found in "hello".. only "hello" to be found.
    Currently i've got two strings, one is the sentance (String input), and one is the word to be found in the sentance (String word). I need the program to find the WORD, and then go back and search for the word again and again and again until it reaches the end of the string.
    This is what I've got thus far:
              for(i = 0; i < input.length(); i++)
                   // This statement checks the string "input" for the string "word" starting at offset 0 (as this is what the variable was first defined as)
                   if(input.indexOf(word, offset) >= 0)
                        // If it finds the word at all, this line increases the offset ahead of this word so it doesn't simply find the same word again
                        offset = offset + (input.indexOf(word)) + (word.length());
                        times++;
              }At the moment this searches for the sub-string, not the WORD which is what I would like it to do.
    What's the easiest way of going about this? I've been fiddling around trying to add extra sections to the if statement, for example
    if((input.indexOf(word, offset) >= 0) && (input.charAt(offset +1) == 32))(32 as in the ASCII character for a space, which would do what I wanted it to do)
    But I eventually get errors because at some stage or another the charAt is going to be higher than the actual length of the String. Plus, this only looks if there's a space next to the word - a word can be valid if it has a ! next to it for example, or a comma...
    Thanks for any help :)
    viddy

    I think there's a word boundary marker in regex. So it'd be "\\w+hello\\w+" or whatever the marker is, to be used with a Pattern instance.

  • Itunes script to detect gaps in track numbers within an album

    Is there an iTunes script out there that will detect gaps in the track numbers within an Artist & Album?    This would be useful to detect incorrectly numbered tracks that could reveal an error in the whole file's tagging that occurred for whatever reason.   I'm picturing a process that would sort your library by Artist+Album+Tracknumber, then look for any numbering gaps and if found, display the 2 files with the gap in-between into a playlist for the user to evaluate for problems.   Or perhaps this is not possible?

    Looks like this does most of what you want in that it identifies incomplete albums. You'd still have to see which tracks were missing: http://www.enilnomi.net/cgi-bin/blosxom.cgi/dltext/findincompletealbums.dl
    I'm assuming from the product info you're looking for an AppleScript for iTunes for OS X. If you want one for Windows I could probably oblige.
    tt2

  • Searching for a substring within a string

    can someone reccomend a simple way to search for a substring within a string and count the number occurences of that substring.
    The substring and the string will be provided as command line parameters.
    Thanks
    gg

    A simple way would be to use the indexOf methods in String:
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
    Not sure what this has to do with event handling though :-P

  • Replacing numbers in a string

    Is it possible to look through a string find any 0's and replace them with a random Integer generated before?

    Take a look at the methods in the String API and see
    if you can find one that will replace all
    occurrences of something within a string with
    something else.
    ~@OP:
    I was assuming you wanted to replace every zero with a different (pseudo) random number, in which case you can use replaceFirst(...) as I suggested.
    If you want to replace every zero with the same (pseudo) random number, use yawmark's approach.

  • Can you suggest a group messaging app where recipients can't see all the phone numbers within the group?

    Can you suggest a group messaging app where recipients can't see all the phone numbers within the group?  My friends are complaining that they can see all the people in the group; also when I get a response from some in the group, it comes to me ane many others in the goup - its like they've replied all. 
    Any help would be appreciated.
    iPhone 4; iOS5

    Sorry it hasn't worked out for you. I threw together a simple project that uses rectangles to represent your Bike and wheel groups. They all animate across the canvas in the bike group and the wheels rotate. I have attached screen shots so you can see how they are constructed.
    This image showsthe bike group where the orange rectangle and green circle represent the frame. The white rectangles represent wheels and the green and red rectangles I threw in to represent a wheel that has multiple objects in its group as your wheels do.
    Here the animation across the screen has started and notice all wheels rotating and staying with the frame.
    Again a little further down the timeline.
    I put this one in so you could see the group bounding box around the red and green wheel Good luck with your restart on this project and I hope these screen shots are helpful.

  • Findind out the number of lines within a string - using buffered reader

    Hi All,
    Want to know the number of lines within a string..Sample code is there for reference..could u help me out how to have the number of lines in a string without java comments (i.e string within /**------*/ and // should be eliminated)
    public class ReadLines {
         public static void main(String[] args) throws Exception{
              ReadLines rl = new ReadLines();
              rl.readLines();
         void readLines() throws Exception{
              String str = "/** This is a test message\n"+
                   "* for testing\n"+
                   "*/\n"+
                   "import java.io.*\n"+
                   "// this is again comment\n"+
                   "public class ReadLines {\n"+
              BufferedReader reader = new BufferedReader(new StringReader(str));
              String line = "";
              int count = 0;
              while ((line = reader.readLine())!= null )
                   //line = reader.readLine();
                   count++;
              System.out.println(count);
    }Thanks
    MK

    Hi
    What you need to do is parse the file in such a way that you read /*, */ and // as tokens. By that I mean rather than read a line at a time (although I'm sure you could), read it character by character. So every time you reach a new line character then increment the counter. But there are two casaes when you don increment the counter they are:
    If you encounter a / followed by * then keep reading but if you encounter a newline character then DONT increment the counter ONLY continue counting when you read a * followed by a / (as this is the end of the comment)
    If you encounter / followed by another / then do not count that particular line and go to the next line and continue counting from there.
    Where I've written 'continue counting' this is subject to the lines that follow not conforming to the above two cases.
    I hope this helps.

  • Get number of character within a String by number of pixels

    How can i get the number of character within a String
    by a width value...
    for example..
    i have a String = "1234567890abcdefghi.........."
    and when i give the width "10"
    i will get the String "12".
    or the number of charcter..
    or somthingggggggggggggggg
    please help..
    Shay

    i solved this...
    by doing somthing similar..
    i made a for loop on all character
    and evrey time i am get a sub string from the 0 till the loop index..
    and i am chashing the last string
    so when a sub width is greater the the requested width
    i am returning the lst cashed result
    thanks.. all..

  • Increment a number within a string

    Hi!
    How can I increment a number within a string ?
    This code doesn' t provide the rigth result
    DATA zahl TYPE I.
    DO 10 TIMES.
    zahl = zahl +  1.
    write:/ 'HALLO zahl'.
    ENDDO.

    Hello,
    Change the code like this.
    DATA ZAHL TYPE I.
    DATA: LV_ZAHL(8),
          CHAR(255).
    DO 10 TIMES.
      ZAHL = ZAHL + 1.
      WRITE: ZAHL TO LV_ZAHL.
      CONCATENATE 'HALLO' LV_ZAHL INTO CHAR.
      CONDENSE CHAR NO-GAPS.
      WRITE:/ CHAR."'HALLO'NO-GAP,ZAHL NO-GAP.
    ENDDO.
    Regards,
    Vasanth

  • OBIEE - Find position of the last occurrence of a charcter within a string.

    Hi,
    I have a requirement in 11.1.1.6.9 to be locate the position of the last occurrence of a character within a string.
    i.e. Given the following, I would want to locate the last "/":
    This/is/an/exampleI would like to return a value of 11. Now, there could be any number of "/" so I can't always locate the nth one - it must be the last one.
    Anyone any ideas?
    Thanks,
    John

    Your requirement is not complete. just in case you want to extract the last part 'example' just use substring and replace to trim up to required part.
    You may have to go for the same for multiple times.
    ETL is the best to handle this than BI.
    BTW: Check this How to use locate function if multiple occurences of same character
    Edited by: Srini VEERAVALLI on May 10, 2013 10:25 AM
    Good that given link is helped you to solve it ;)
    Edited by: Srini VEERAVALLI on May 13, 2013 7:47 AM

Maybe you are looking for

  • A list of all staff currently employed by one org

    User want list of all staff currently employed by XXXX organization. I ran this query   SELECT papf.employee_number, papf.first_name, papf.last_name     FROM per_all_people_f papf,          per_all_assignments_f paaf,          hr_all_organization_uni

  • HT4910 Can I backup my Powerpoint and Word docs on iCloud

    I want to be able to access my Powerpoint docs via iCloud, is it possible?

  • Keyboard problems on a Macbook Pro Retina 15 Inch

    Here's a new one for the absolute Geniuses out there. I recently had a battery repair on my Macbook Pro Retina Display, which was successful. After using my computer normally for another week, my keyboard has become ill. My RIGHT SHIFT key doesn't wo

  • USING CS6 creating icons using pixel view...

    why has the pixel grid shifted on the document .5 of a pixel when i re-open the image? is there a way to prevent this? Is it fixed in an update? doing pixelXpixel work, this a real pain in the but

  • Does using iCloud eliminate the ability to use wired syncing?

    I turned on iCloud on the iPhone (it has the updated os) but now any of my pics that were previously synced from with my computer through itunes have disappeared. Is the choice one or the other but not both?  I haven't actually added iCloud to our co