Identifying patterns in a string & replacing all characters with 1st digit

Morning folks. Interesting problem on hand. I have a situation where I have a varchar2 text field where I have different paterns of a sequence of numbers somewhere in the string. I guess, I could write a function where by I accept the whole string and then identify one of the patters below and then finally replace only the recognized pattern with the first digit all the way through to the end of that pattern.
The catch here is that there could be free text before and after the string but there will be spaces when free text ends and the patern begins.
Here are a few patterns I would be interested in. The MAX length is 19 as in Cases 1 and 3.
1. 9999 9999 9999 9999
2. 9999999999999999
3. 9999-9999-9999-9999
4. 9999-9999-99-99999
5. 9999-999999-99999So, here would be an example of the problem in hand :
Call received on 9/22/2009.
5123-4532-8871-9876
Please follow up by 10/22/2009So, the desired output would be :
Call received on 9/22/2009.
5555-5555-5555-5555
Please follow up by 10/22/2009Any ideas ? I am stumped at the fact of before and after text in the string, hence the question for you guys !
Thanks !

Here is another solution. However there has to be a better way! (I'm not a regular expression expert).
SQL> WITH test_data AS
  2  (
  3          SELECT 'Call received on 9/22/2009.
  4          1232 3456 8765 3456
  5          Please follow up by 10/22/2009' AS DATA FROM DUAL UNION ALL
  6          SELECT 'Call received on 9/22/2009.
  7          1232345687653456
  8          Please follow up by 10/22/2009' AS DATA FROM DUAL UNION ALL
  9          SELECT 'Call received on 9/22/2009.
10          1232-3456-8765-3456
11          Please follow up by 10/22/2009' AS DATA FROM DUAL UNION ALL
12          SELECT 'Call received on 9/22/2009.
13          1232-3456-86-3456
14          Please follow up by 10/22/2009' AS DATA FROM DUAL UNION ALL
15          SELECT 'Call received on 9/22/2009.
16          1232-345687-3456
17          Please follow up by 10/22/2009' AS DATA FROM DUAL
18  ), substring AS
19  (
20          SELECT  DATA AS SOURCE
21          ,       REGEXP_INSTR
22                  (
23                          DATA
24                  ,       '(([[:digit:]])+[[:space:]|-]){1,}'
25                  ) AS PATSTART
26          ,       REGEXP_SUBSTR
27                  (
28                          DATA
29                  ,       '(([[:digit:]])+[[:space:]|-]){1,}'
30                  ) AS PATTERN
31          ,       19 AS MAXLENGTH
32          FROM    test_data
33  )
34  SELECT  SUBSTR
35          (
36                  SOURCE
37          ,       1
38          ,       PATSTART-1
39          ) ||
40          TRANSLATE
41          (
42                  PATTERN
43          ,       '0123456789'
44          ,       LPAD
45                  (
46                          SUBSTR
47                          (
48                                  PATTERN
49                          ,       1
50                          ,       1
51                          )
52                  ,       10
53                  ,       SUBSTR
54                          (
55                                  PATTERN
56                          ,       1
57                          ,       1
58                          )
59                  )
60          ) ||
61          SUBSTR
62          (
63                  SOURCE
64          ,       PATSTART + MAXLENGTH
65          )       AS NEW_STRING
66  FROM substring
67  /
NEW_STRING
Call received on 9/22/2009.
        1111 1111 1111 1111
        Please follow up by 10/22/2009
Call received on 9/22/2009.
        1111111111111111
      Please follow up by 10/22/2009
Call received on 9/22/2009.
        1111-1111-1111-1111
        Please follow up by 10/22/2009
Call received on 9/22/2009.
        1111-1111-11-1111
       Please follow up by 10/22/2009
Call received on 9/22/2009.
        1111-111111-1111
      Please follow up by 10/22/2009
SQL>

Similar Messages

  • Replace all occurrence with range - issue

    Hi,
    I have a range with "letters" like ":" or "-" or "."
    Note: all entries are with option = "equal"
    Now i need to "replace all occurrences" of "all entries in that range" with space.
    idea:
    loop at range assigning <range>.
    replace all occurrences of <range>-low in aaa with space
    endloop.
    Any better ideas ?
    Regards,
    Gordon

    Sorry but i think my question was not clear.
    is there another way instead of using the "loop" ?
    The translate or replace statement is not the problem
    thx,
    Gordon

  • String replace All using RegExp

    var myString:String="<font face='arial' size='14'>ZX</font><span class='cssid'>some Text </span><font face='arial' size='14'>USP</font>"
      var fontName:String="Vardana"
    var fontSize:String="11"
      var regexp:RegExp = /<font.*?>/;
      myString = myString.replace(regexp, "<font face='"+fontName+"' size='"+fontSize+"' >");
    above scripte replacing only "<font face='arial' size='14'>ZX</font>"
    i need to replace   : "<font face='arial' size='14'>ZX</font><span class='cssid'>some Text </span><font face='arial' size='14'>USP</font>"

    var regexp:RegExp = /<font.*?>/igm;

  • Replacing unauthorized characters with space

    Hi friends,
    There is a set of authorized characters. The authorized characters are
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<space>
    If any character other than these characters should be replaced with space.
    For example, "I like foot-ball" should be changed to "I like foot ball"
    "Where are you?" should be changed to "Where are you"
    "red / blue" should be changed to "red   blue"
    I use Oracle 11.2.
    Thanks in advance!

    Using regular expression you can do this.
    SQL> with t
      2  as
      3  (
      4  select 'I like foot-ball' str
      5    from dual
      6  )
      7  select str
      8       , regexp_replace(str, '[^a-z0-9[:space:]]', ' ', 1, 0, 'i') new_str
      9    from t;
    STR              NEW_STR
    I like foot-ball I like foot ball
    You can read more about regular expression from the document.
    Using Regular Expressions in Oracle Database
    Message was edited by: Karthick_Arp
    Edited the Pattern after seeing franks post.

  • Replacing Special Characters With Its Actual Value

    Hi All,
    Does anyone has any idea how to replace an extended character (ASCII value ranging from 128 to 255) to its actual character set in SQL/PLSQL?
    For example: “½” needs to be replaced to “1/2”
    “¼” needs to be replaced to “1/4”
    Ultimately if the value is “California 71 ½ ” then the result should be “California 71 1/2”.
    Thanks for your time!
    Regards,

    user10088255 wrote:
    Hi All,
    Does anyone has any idea how to replace an extended character (ASCII value ranging from 128 to 255) to its actual character set in SQL/PLSQL?You can also use POSIX Character Equivalence Class to match characters having the same base character as the character you specify.
    --Extended ASCII (ISO Latin-1):
    á     #225
    â     #226
    ã     #227
    ä     #228
    å     #229
    æ       #230
    SQL> select regexp_replace('á,â,ã,ä,å,æ','[[=a=]]','a') str from dual;
    STR
    a,a,a,a,a,a

  • How to replace special characters with html code characters automatically?

    A colleague and I work on these html pages. They eventually end up as emails, but we have the cold fusion server to pre process them. One thing we are trying to do is eliminate problems caused by unencoded copyright, trademark and smart quote symbols.
    How could I create an array of find / replace commands in the header so it processes the HTML with correct character codes.
    I"m not cold fusion aware, so any kind of starter info would be great. Eventually I might add more replacements to the array.
    As an example TM (font character) would process to &trade; and a smart quote or apostrophe would process to a straight one. an en dash character would become &ndash;
    Because we copy paste from places, this often happens and it seems like cold fusion could solve the problem quickly and repeatedly all at once.
    thanks for any help
    -smick

    CF has a built in HTMLEditFormat function for handling <  &  > characters.  For handling trademark and smart quote characters you might try searching for a user defined function at http://cflib.org or writing a user defined function yourself that will handle the specific characters needed in your application.

  • Does trim replace some characters with control code versions in xml?

    I am using trim to remove extra white space and linefeeds from xml files and it works fine except that occasionally it replaces xml close element symbols (>) with the control code > used to delineate a > symbol that is not to be interpreted as as the xml character. What gives here? I thought all trim did was eliminate leading and trailing characters whose code was greater than '\u0020'.
    I am using Java 1.5 but this happened with 1.4 as well.

    Yes,
                             <md.decideddate>20060612</md.decideddate>
    apparently has the final '>' replaced by &gt.
    This does not happen consistently and can only be seen when loaded to IE. The Framework that I am working with in Websphere sees the error but neither XMLSpy or Eclipse has a problem with the file.
    Here's what I get when I load the file to IE:\
    An invalid character was found in text content. Error processing resource 'file:///C:/Projects/Rex/testdata/input/content/R...
    <md.dates><md.filedate>May 26, 2006</md.filedate><md.decideddate>20060526</md.decideddate&g...
    I find this very strange.

  • Replace all footage with different format

    Hi All,
    So I am aware about like changing some files by like renamming or moving the folder and opening the project and then pointing it to the new directory/whatever and that works great.
    I am helping out a friend who does sound who's client is a mess and I need to figure out a fast way to fix this.
    Long story short the poor kid shot on a redcam but had everything converted to .mov 720x480 files and edited in premiere elements. Well... The sound guy can't get an OMF from there so I took everything and imported it into premiere pro and started fixing a couple bits up and exported the OMF. Now I found out that the kid still has the R3D files. so I would like to replace every .mov and .mp4 file in this project to the r3d of the same name with just the r3d extension.
    Meaning when I tried to move the other files and start replacing i had to manually locate each r3d and that would take forever...
    I want to change the files to the much better quality ones, setup a proper sequence, keep his edits, and then speedgrade it for him but I am not willing to invest the time of manually replacing each file.
    any ideaS?

    Hi Jim,
    I moved all the R3Ds (that's all he has, not other files associated to it) into the same folder so they are together, and that did not work
    I feel bad for this kid as he has invested and is trying to do something, but doesn't know how. I may end up doing it the long way.

  • Replace of characters with storeb prozedure

    Hi,
    I want to write a stored prozedure that has as source and target a varchars2 field.
    What I want wo do is like the follwing:
    source:a, k, ch, c
    target:d, o, v, ie
    Word example:
    source: jed
    target: and
    The text of the source field has to be analysed and transformed not only letter by letter, because some combinations have two letters like the example with ch.
    Thanks for help,
    Walter

    Hi,
    Why not have a lookup table with source, target and a sequence to know the order to replace. Because of you need to replace ch and c, you need to know the first to be replace, is ch or c ? The result is not the same.
    SQL> select * from replace;
    SO TA        SEQ
    a  d           1
    k  o           2
    ch v 3
    c ie 4
    j  a           5
    e  n           6
    d  d           7
    7 rows selected.
    SQL> create or replace function freplace(wstring varchar2)
      2  return varchar2
      3  as
      4  w_string varchar2(4000):=wstring;
      5  begin
      6  for x in (select * from replace order by seq) loop
      7      w_string := replace(w_string,x.source,x.target);
      8  end loop;
      9  return w_string;
    10  end;
    11  /
    Function created.
    SQL> select freplace('School') School, freplace('jed') jed from dual;
    SCHOOL   JED
    Svool         and
    SQL> truncate table replace;
    Table truncated.
    SQL> insert into replace values ('a','d',1);
    1 row created.
    SQL> insert into replace values ('k','o',2);
    1 row created.
    SQL> insert into replace values ('c','ie',3);
    1 row created.
    SQL> insert into replace values ('ch','v',4);
    1 row created.
    SQL> select * from replace;
    SO TA        SEQ
    a  d           1
    k  o           2
    c ie 3
    ch v 4
    SQL> select freplace('School') from dual;
    FREPLACE('SCHOOL')
    SiehoolNicolas.
    Message was edited by:
    N. Gasparotto

  • Help needed with String replace!

    Hi,
    I would like to replace all '\' characters with '/' in my string, ie:
         mystring.replace('\','/');
    Howeve, it complain about the '/' (Unclosed character literal).
    Any suggestions?
    Thanks

    Show us the line, you are probably using your regex incorrectly.
    In order to get the '\' you have to escape it (the '\' char. is used as the escape character so that you can look for things like " ' and new lines by useing \" \' and \n. Otherwise, how would java know you are looking for quotes and not closing your string?) As a consequence, your regex should look like '\\" for the \.
    The replace statement should probably be:
    string.replace("\\", "/");

  • Looking for, and replace special characters

    Hi
    I am quite new to AppleScript and can't figure this out. Any help would be appreciated.
    I have received several (a lot of) folders containing images with some strange characters in the file names. The images has to go to web, and I want to replace those characters with some that are web friendly. The characters in question is some Swedish A's and O's (Ä, ä, Ö, ö) and one that looks like the Apple Command symbol. (I was told this one is a combination of a and e).
    Then, I would like to replace all spaces between the words in the file names with an underscore.
    In addition, all image file names start with capitals and I would like to replace these as well.
    Thanks
    Neal
    G5   Mac OS X (10.4.6)  

    Here's a modified version of the standard script:
    try
    tell application "Finder" to set the source_folder to (folder of the front window) as alias
    on error -- no open folder windows
    set the source_folder to path to desktop folder as alias
    end try
    display dialog "Search and replace in:" buttons {"File Names", "Folder Names", "Both"} default button 3
    set the search_parameter to the button returned of the result
    repeat
    display dialog "Enter text to find in the item names:" default answer "" buttons {"Cancel", "OK"} default button 2
    set the search_string to the text returned of the result
    if the search_string is not "" then exit repeat
    end repeat
    repeat
    display dialog "Enter replacement text:" default answer "" buttons {"Cancel", "OK"} default button 2
    set the replacement_string to the text returned of the result
    if the replacement_string contains ":" then
    beep
    display dialog "A file or folder name cannot contain a colon (:)." buttons {"Cancel", "OK"} default button 2
    else if the replacement_string contains "/" then
    beep
    display dialog "A file or folder name cannot contain a forward slash (/)." buttons {"Cancel", "OK"} default button 2
    else
    exit repeat
    end if
    end repeat
    display dialog "Replace “" & the search_string & "” with “" & the replacement_string & "” in every item name?" buttons {"Cancel", "OK"} default button 2
    tell application "Finder"
    set the item_list to every item of entire contents of source_folder
    tell me
    set item_list to reverse of the item_list
    end tell
    set source_folder to source_folder as string
    repeat with i from 1 to number of items in the item_list
    set the_name to name of item i of the item_list
    set this_item to item i of the item_list
    set this_info to properties of this_item
    set the current_name to the_name
    set change_flag to false
    repeat with this_char from 1 to (count items of search_string)
    if the current_name contains item this_char of (search_string) then
    if the search_parameter is "Folder Names" and ¬
    folder of this_info is true then
    set the change_flag to true
    else if the search_parameter is "File Names" and ¬
    folder of this_info is false then
    set the change_flag to true
    else if the search_parameter is "Both" then
    set the change_flag to true
    end if
    if the change_flag is true then
    set this_item to item i of the item_list
    -- replace target string using delimiters
    set AppleScript's text item delimiters to the item this_char of search_string
    set the textitemlist to every text item of the current_name
    set AppleScript's text item delimiters to the item this_char of replacement_string
    set the newitemname to the textitemlist as string
    set AppleScript's text item delimiters to ""
    set the current_name to newitemname
    end if
    end if
    end repeat
    my setitem_name(thisitem, current_name)
    end repeat
    end tell
    beep 2
    on setitem_name(thisitem, newitemname)
    tell application "Finder"
    --activate
    set the parentcontainerpath to (get the container of this_item) as text
    if not (exists item (the parentcontainerpath & newitemname)) then
    try
    set the name of this_item to newitemname
    return this_item
    on error the error_message number the error_number
    if the error_number is -59 then
    set the error_message to "This name contains improper characters, such as a colon (:)."
    else --the suggested name is too long
    set the error_message to error_message -- "The name is more than 31 characters long."
    end if
    --beep
    tell me to display dialog the error_message default answer newitemname buttons {"Cancel", "Skip", "OK"} default button 3
    copy the result as list to {newitemname, button_pressed}
    if the button_pressed is "Skip" then return 0
    my setitem_name(thisitem, newitemname)
    end try
    else --the name already exists
    --beep
    tell me to display dialog "This name is already taken, please rename." default answer newitemname buttons {"Cancel", "Skip", "OK"} default button 3
    copy the result as list to {newitemname, button_pressed}
    if the button_pressed is "Skip" then return 0
    my setitem_name(thisitem, newitemname)
    end if
    end tell
    end setitemname
    This script variant works by accepting a source string in the form "AB" and desired string "CD". When run, ABCA will become CDCC with the sample strings.
    (19254)

  • About REPLACE ALL functionality

    Dear All,
    I have one string which contains '#' in between. And I want to replace all these '#' with ' ' (ie blank SPACE)..
    For this I am using:-
    REPLACE ALL OCCURRENCES OF '#' IN L_TEXT WITH ' '.
    But to my greatest surprise, its not able to replace it saying sy-subrc = 4 ie its not able to locate '#'.
    I have observed following:-
    1. Suppose L_TEXT = 'corrective action## is that# to be #taken'
    then replace all fails.
    2. But suppose L_TEXT = 'corrective action # # is that # to be # taken'
    then its works.
    I tried the option of
    REPLACE ALL OCCURRENCES OF REGEX '#*' IN L_TEXT WITH ' '.
    But its putting ''#" after every character !!!
    And the same functionality works with CRM4.0's ABAP editor but now when i am using it in CRM2007's ABAP editor, its not woking.
    I have tried it in ABAP editors of other systems like PRD n all. Its working there too.
    Can anybody please shed some light on this?
    regards,
    Amey Mogare

    Yes Matt,
    I suspect its not the actual character "#". !!!!
    Actually in one of the CRM transaction GUI, there is a Text Box where user can enter his Survey details. In this, if he enters a newline then in FM i'm getting it as "#"... What I mean is if I write :-
    Heading 2: h2.
    Containment text
    is as follows
    line 1
    line2
    Heading 2: h2.
    Then in FM's field its represented as
    Heading 2: h2.
    Containment text# is as follows# line 1# line2
    Heading 2: h2.
    But this is getting messed up in when we dump it into excel sheet.
    So how do i replace these with Spaces?
    sample code line would be very helpful.
    Thanks a lot for pointing this out.
    regards,
    Amey

  • Replace encoded characters in URL

    Hi gurus,
    I have the following requirement and I don't know how to solve it in the best way.
    I have a Z transaction for uploading a local file. This file contains URL's and after upload, there are stored in SAP.
    I need to check this URL and replace encoded characters with corresponding codes, for example: space -> %20
    How can I do this? I've been looking for a solution, but I haven't found anything usefull yet.
    Any ideas?
    Thanks a lot!

    Have a look at class CL_HTTP_UTILITY. There are some methods which looks promising.
    The method ESCAPE_URL is waht you needed.
    pass UNESCAPED = 'http://forums.sdn.sap.com/edit!default.jspa?messageID=11060123'
    output = HTTP%3a%2f%2fFORUMS%2eSDN%2eSAP%2eCOM%2fEDIT%21DEFAULT%2eJSPA%3fMESSAGEID%3d11060123
    & for vice versa use UNESCAPE_URL
    Edited by: Keshav.T on Feb 7, 2012 2:23 PM

  • [SOLVED] Find all users with a MAILTO option in their crontab

    Anyone know if this is possible? I have a script that lists all scheduled cronjobs but I need to find out which users have email notifications configured.
    If anyone else wants it, here is the script I use to check all user's crontabs. I did not write this.. just found it a while back.
    #!/bin/bash
    # System-wide crontab file and cron job directory. Change these for your system.
    CRONTAB='/etc/crontab'
    CRONDIR='/etc/cron.d'
    # Single tab character. Annoyingly necessary.
    tab=$(echo -en "\t")
    # Given a stream of crontab lines, exclude non-cron job lines, replace
    # whitespace characters with a single space, and remove any spaces from the
    # beginning of each line.
    function clean_cron_lines() {
    while read line ; do
    echo "${line}" |
    egrep --invert-match '^($|\s*#|\s*[[:alnum:]_]+=)' |
    sed --regexp-extended "s/\s+/ /g" |
    sed --regexp-extended "s/^ //"
    done;
    # Given a stream of cleaned crontab lines, echo any that don't include the
    # run-parts command, and for those that do, show each job file in the run-parts
    # directory as if it were scheduled explicitly.
    function lookup_run_parts() {
    while read line ; do
    match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
    if [[ -z "${match}" ]] ; then
    echo "${line}"
    else
    cron_fields=$(echo "${line}" | cut -f1-6 -d' ')
    cron_job_dir=$(echo "${match}" | awk '{print $NF}')
    if [[ -d "${cron_job_dir}" ]] ; then
    for cron_job_file in "${cron_job_dir}"/* ; do # */ <not a comment>
    [[ -f "${cron_job_file}" ]] && echo "${cron_fields} ${cron_job_file}"
    done
    fi
    fi
    done;
    # Temporary file for crontab lines.
    temp=$(mktemp) || exit 1
    # Add all of the jobs from the system-wide crontab file.
    cat "${CRONTAB}" | clean_cron_lines | lookup_run_parts >"${temp}"
    # Add all of the jobs from the system-wide cron directory.
    cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */ <not a comment>
    # Add each user's crontab (if it exists). Insert the user's name between the
    # five time fields and the command.
    while read user ; do
    crontab -l -u "${user}" 2>/dev/null |
    clean_cron_lines |
    sed --regexp-extended "s/^((\S+ +){5})(.+)$/\1${user} \3/" >>"${temp}"
    done < <(cut --fields=1 --delimiter=: /etc/passwd)
    # Output the collected crontab lines. Replace the single spaces between the
    # fields with tab characters, sort the lines by hour and minute, insert the
    # header line, and format the results as a table.
    cat "${temp}" |
    sed --regexp-extended "s/^(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(.*)$/\1\t\2\t\3\t\4\t\5\t\6\t\7/" |
    sort --numeric-sort --field-separator="${tab}" --key=2,1 |
    sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
    column -s"${tab}" -t
    rm --force "${temp}"
    Last edited by thelastknowngod (2011-11-28 22:14:33)

    Perhaps I'm missing something here, but...
    grep -i MAILTO /var/spool/cron/*

  • CS4 can't input special characters (|\#) with alt+shift

    Very strange,
    I can input all characters with alt+shift except for:
    * alt+shift+l normally outputs: |
    * alt+shift+/ normally outputs: \
    * alt+shift+£ normally outputs: #
    I have an EN_US version, and I work with an azerty-keyboard
    This was an issue with cs3 too
    anybody has a clue why I can't input these characters?
    thanks

    No idea, but maybe due to security reasons, because "&&" is a logical AND, and "||" is a logical OR, and "//" could start a comment, through input boxes these could actually alter the internal program and one maybe able to bypass security codes or do other imaginative things. In fact similar things have been widely used in PHP language by hackers, one of their methods is known as "xss" or cross site scripting through which a badly regulated/filtered/controlled user input can be exploited.

Maybe you are looking for