knowledge_seeker
knowledge_seeker

Reputation: 372

How can I replace a string which comes with some pattern and keeping the rest same?

I have a string something like

val changeMe= "select myTable.x,myTable.y,myTable.myTable from myTable join myTable2 ON myTable.x = myTable2.x" 

and I just want to replace the table name myTable with another string like myTable3 and want to keep the column in myTable.myTable as the same myTable. and the output string should be like

val outputString= "select myTable3.x,myTable3.y,myTable3.myTable from myTable3 join myTable2 ON myTable3.x = myTable2.x"

Please let me know how can I do that using regex in scala?

Thanks.

Upvotes: 0

Views: 79

Answers (3)

jwvh
jwvh

Reputation: 51271

Sounds like a job for replaceAll().

changeMe.replaceAll("(?<![.])myTable(?!2)", "myTable3")
//res0: String = select myTable3.x,myTable3.y,myTable3.myTable from myTable3 join myTable2 ON myTable3.x = myTable2.x

Use negative look-behind and look-ahead to help isolate the target string from its imitators.

Upvotes: 1

vks
vks

Reputation: 67988

Use a lookbehind.

(?<!\\.)\\bmyTable\\b

See demo.

https://regex101.com/r/OFNGdK/1

Upvotes: 2

Mohammad Javad Noori
Mohammad Javad Noori

Reputation: 1227

You can use : (?<=[, ])myTable(?=[^2])

Demo

Upvotes: 1

Related Questions