Add space before each Capitalized word (minus the 1st one) using Scala code

142 views Asked by At

I'm new to Scala... so far I'm really liking it. :)

Right now I'm playing with Play Framework and I'm amazed by how straightforward it is to get going.

Well... the problem at hand is that I'd like to make a string as the following one more readable:

UsersGroupedByRegistrationMonthYear.csv

The output should be:

Users Grouped By Registration Month Year.csv

Can you lend a hand?

3

There are 3 answers

0
jwvh On BEST ANSWER

Not regex, but a pretty straight forward approach.

val str = "UsersGroupedByRegistrationMonthYear.csv"
str.flatMap(c => if (c.isUpper) Seq(' ', c) else Seq(c)).trim
0
anubhava On

You can search using this regex with 2 capturing groups:

([a-z0-9])([A-Z])

and replace using this pattern:

$1 $2

RegEx Demo

Code:

repl = input.replaceAll("([a-z0-9])([A-Z])", "$1 $2");
0
Dmitry Aleks On

One alternative is to use String.split with regex lookarounds to tokenize your string by caps without throwing them away and then to combine tokens back into a string with spaces between tokens:

val in = "UsersGroupedByRegistrationMonthYear.csv"
val out = in.split("(?=[A-Z])").mkString(" ")

println("\"%s\"\nbecomes\n\"%s\"".format(in, out))

This yields:

"UsersGroupedByRegistrationMonthYear.csv"
becomes
"Users Grouped By Registration Month Year.csv"