scalauser
scalauser

Reputation: 1327

dynamic string replace in scala

I have an example string below. Need to do string replace and add _tmp in the original string. Can someone please help ?

Ex: 1    "name,name|substr(city,53,17),coun"
Ex :2    "age,age|substr(zip,10,16),zipcode|substr(street,19,20),place"

Expected result:

Expected Answer 1 : "name,name|city_tmp,coun"
Expected Answer 2 : "age,age|zip_tmp,zipcode|street_tmp,place"

Currently I am splitting the original string and doing for loop to match each string contains the word "substr" and replacing it with spaces.

Then further I split that element and create an array and replace the first element of the array with _tmp.

I think there should be a elegant solution for this. Can someone advise?

Upvotes: 1

Views: 435

Answers (1)

jwvh
jwvh

Reputation: 51271

A basic case of search and replace.

//"sub string" regular expresion
val ssRE = raw"substr\((\w+),\d+,\d+\)".r

val exA = "name,name|substr(city,53,17),coun"
ssRE.replaceAllIn(exA,"$1_tmp")
//res0: String = name,name|city_tmp,coun

val exB = "age,age|substr(zip,10,16),zipcode|substr(street,19,20),place"
ssRE.replaceAllIn(exB,"$1_tmp")
//res1: String = age,age|zip_tmp,zipcode|street_tmp,place

Upvotes: 2

Related Questions