loyalflow
loyalflow

Reputation: 14879

Is scala as succinct with regular expressions like Ruby?

In Ruby if you wanted to replace multiple ! marks to a single ! you can do:

 text.gsub!(/!+/, '!') 

Does scala have a succinct way of doing something similar?

Upvotes: 0

Views: 108

Answers (3)

Randall Schulz
Randall Schulz

Reputation: 26486

In thinking about this question, the thought that it would be possible to create a Scala 2.10+ string interpolator to somewhat streamline the creation of Regex instances relative to the current .r method. As soon as it occurred to me, I figured someone must have already given this a try, and in fact they had.

Check it out: Scala Regex StringContext

Upvotes: 0

Brian
Brian

Reputation: 20285

If you really want to use a regular expression, this will do. The .r in Scala turns the String into a Regex.

scala> val s = "This is exciting!!!"
s: String = This is exciting!!!

scala> "!+".r.replaceAllIn(s, "!")
res14: String = This is exciting!

Upvotes: 1

arshajii
arshajii

Reputation: 129517

Yes, you can simply do:

text = text.replaceAll("!+", "!")

Note that Scala strings are instances of java.lang.String.

Upvotes: 4

Related Questions