cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
cancel
Showing results for 
Search instead for 
Did you mean: 

How to parse/extract/format a string based a pattern?

Databrickguy
New Contributor II

How to parse, extract or form a string based on a pattern?

SQL server has a function which will format the string based on a pattern. example,

a string is "abcdefgh", the pattern is XX-XX-XXXX,

the the string will be "ab-cd-efgh".

How to archive this with a function?

1 ACCEPTED SOLUTION

Accepted Solutions

Aviral-Bhardwaj
Esteemed Contributor III

@Tim zhang​ ,

thanks for your code, and here is your answer

image 

I asked this question in Stackoverflow and got this answer

Here is the Stackoverflow link- https://stackoverflow.com/questions/74845760/how-to-parse-a-pattern-and-use-it-to-format-a-string-us...

Please select my this answer as the best answer,it will be really encouraging

Thanks

Aviral Bhardwaj

View solution in original post

6 REPLIES 6

Aviral-Bhardwaj
Esteemed Contributor III

Hey @Tim zhang​ ,

This is silly answer but this can give you some idea

image 

or you can use for loop here,

Thanks

Aviral

Thanks a lot of your replay @Aviral Bhardwaj​ 

I try to not hard code it and eventually turn it to a function. This is a initial raw code, but it has problem,

val pattern="XX-***-XXXX-***";

val item="abcdefghijkl"

val patternindex=pattern.lastIndexOf("-");

val patternupdated= pattern.substring(0,patternindex);

var lenplus = pattern.indexOf("-")

var fitem=item.patch(lenplus, "-", 0)

val result = patternupdated.split("-")

     

    for ( a

    {

     val len= a.length() 

     // Displays output

              

      lenplus = len + lenplus+1

      fitem= fitem.patch(lenplus, "-", 0)

       

          

     println(fitem)

    } 

The result is wrong,

ab-cd-efghijkl

ab-cd-efg-hijkl

ab-cd-efg-hijk-l

Aviral-Bhardwaj
Esteemed Contributor III

@Tim zhang​ ,

thanks for your code, and here is your answer

image 

I asked this question in Stackoverflow and got this answer

Here is the Stackoverflow link- https://stackoverflow.com/questions/74845760/how-to-parse-a-pattern-and-use-it-to-format-a-string-us...

Please select my this answer as the best answer,it will be really encouraging

Thanks

Aviral Bhardwaj

did you get any time to cehck above response @Tim zhang​ 

yea, it works! Thanks!

@Tim zhang​  can you please upvote my answer and make it as best answer,it will be great help

Welcome to Databricks Community: Lets learn, network and celebrate together

Join our fast-growing data practitioner and expert community of 80K+ members, ready to discover, help and collaborate together while making meaningful connections. 

Click here to register and join today! 

Engage in exciting technical discussions, join a group with your peers and meet our Featured Members.