Babu
Babu

Reputation: 891

Replace regex pattern string with empty Scala

   val test = "63760980|0|0.0|0;|0"

the output that I am looking for 63760980||||

I have tried the below way but it removes the characters from diff word/letters

test.replaceAll("0(\\.0|;|)", "").replaceAll("\\|0\\|","\\|\\|")
scala> test.replaceAll("0(\\.0|;|)", "")
res25: String = 637698||||

Upvotes: 1

Views: 285

Answers (1)

jwvh
jwvh

Reputation: 51271

Your requirements are rather ill-defined.

The simple solution is just to remove everything after a bar | character.

"63760980|0|0.0|0;|0".replaceAll("\\|[^|]+", "|")
//res0: String = 63760980||||

But that might be too simple for your actual needs.

More examples, positive and negative, would be useful.


At some point regex might not be the best tool for the job.

"63760980|0|0.0|0;|0|hello|test|768|0.9"
  .split("\\|").map {
    case "0"|"0.0"|"0;" => ""
    case s => s
  }.mkString("|")
//res2: String = 63760980|||||hello|test|768|0.9

But if you have your heart set on a regex solution...

"0;|63760980|0|0.0|0;|0|hello|test|768|0.9|0.0"
  .replaceAll("(?<=(^|\\|))(0|0\\.0|0;)(?=(\\||$))", "")
//res3: String = |63760980|||||hello|test|768|0.9|

...things just get a little more complicated.

Upvotes: 1

Related Questions