Search code examples
sqlibm-midrangedb2-400textpattern

Extract complex text pattern using SQL function


I need to extract a text pattern looking like this:

NN-NNN-NNNNNNNNN 
(2digit,minus, 3digits,minus,9digits)

from along text field. For example, specific field looks like this:

"fsadlk fasldkl jhkjfd khjfasd 11-333-878787618 hfsd uhjkfads"

I need to extract using sql function in the select line the 11-333-878787618. I'm using DB2 AS400 but any SQL function syntax will help.


Solution

  • The following may be useful in that regard; I can add the extraction as well, but I figured that might be understood already, after getting this far:

     create table patterns ( p varchar(65), find_at smallint )
     ;
     insert into  patterns values                                        
      ('fsadlk fasldkl jhkjfd khjfasd 11-333-878787618 hfsd uhjkfads',31)
     ,('weroiu 11-333-8787zz618 oiuwens snkdl osjlwhe'               ,00)
     ,('nm,sdj xhdgweufyen sndh 711-333-878787618 hfsd uhjkfads'     ,26)
     ,('nm,sdj xhdgweufyen sndh 11-333-8787876187 hfsd uhjkfads'     ,25)
     -- ....+....1....+....2....+....3....+....4....+....5....+....6.    
     ;
     select translate(p, '9', '0123456789', '9') as translated
         ,  smallint( locate( '99-999-999999999'              
                    , translate(p, '9', '0123456789', '9') )  
                    ) as located                              
         ,  find_at                                           
     from patterns                                            
     ; -- report from the above query follows:
    TRANSLATED                                                         LOCATED   FIND_AT
    fsadlk fasldkl jhkjfd khjfasd 99-999-999999999 hfsd uhjkfads            31        31
    weroiu 99-999-9999zz999 oiuwens snkdl osjlwhe                            0         0
    nm,sdj xhdgweufyen sndh 999-999-999999999 hfsd uhjkfads                 26        26
    nm,sdj xhdgweufyen sndh 99-999-9999999999 hfsd uhjkfads                 25        25