Vanguard
Vanguard

Reputation: 55

Replacing elements in a string besides the first Occurence In Scala

Im relatively new to Regex and although I know Scala has a method of Utilizing Replace the items before first occurrence but i was wondering if there was a way to get rid of Items in a String After its First Occurrence in Scala.

For Example If i were to have a String Like

"Hello. W.o.r.l.d"
How Would i go about deleting all Following W.

So that it would resemble something akin to

"Hello. World"

Thanks.

Upvotes: 1

Views: 415

Answers (3)

stack0114106
stack0114106

Reputation: 8711

You could also try with indexOf and substring combination

scala> val x = "Hello. W.o.r.l.d"
x: String = Hello. W.o.r.l.d

scala> x.substring(0,x.indexOf(".")+1) + x.split("\\.").tail.mkString
res21: String = Hello. World

scala>

Upvotes: 0

Leo C
Leo C

Reputation: 22439

Here's one approach using a mix of Regex pattern matching and replace:

val s = "Hello. W.o.r.l.d"

val pattern = """(.*?\.)(.*)""".r

s match {
  case pattern(a, b) => a + b.replace(".", "")
  case others => others
}
// res1: String = Hello. World

Note that if the string has no ., it'll be matched by case others.

Upvotes: 3

jwvh
jwvh

Reputation: 51271

No fancy regex required. Just split() and then reconnect.

val noDots = "Hello. W.o.r.l.d".split("\\.")
val res = noDots.head + "." + noDots.tail.mkString  //res: String = Hello. World

This will work correctly if there is only one . in the text but if there is no . then it inserts one at the end of the string.

Upvotes: 4

Related Questions