Reputation: 8711
I need to do a char conversion like this:
accountNumber => ACCOUNT_NUMBER
Where there is a caps letter, then prefix a underscore. If not, just capitalize the character
I tried like below
scala> "accountNumber".map{ x => x match { case x if x == x.toUpper => "_"+x ; case x if x!= x.toUpper => x.toUpper}}.mkString
res38: String = ACCOUNT_NUMBER
It works, but it works differently when there is a digit in between.
scala> "filler51".map{ x => x match { case x if x == x.toUpper && x.isDigit && true => "_"+x ; case x if x!= x.toUpper => x.toUpper}}.mkString
res31: String = FILLER_5_1
I'm expecting it to print FILLER51. For this, I tweaked the code as below, but I'm getting an error.
scala> "filler51".map{ x => x match { case x if x == x.toUpper && !(x.isDigit) => "_"+x ; case x if x!= x.toUpper => x.toUpper}}.mkString
scala.MatchError: 5 (of class java.lang.Character)
at .$line40$$read$$$anonfun$1(<console>:12)
at .$line40$$read$$$anonfun$1$adapted(<console>:12)
at $$Lambda$1399/645018917.apply(Unknown Source)
at ap(StringOps.scala:29)
... 28 elided
Upvotes: 1
Views: 581
Reputation: 1892
Please use the below approach
scala> "filler51".map(x=>if(x>='A' && x<='Z') '_'.toString+x.toString else x.toString)
.mkString
.toUpperCase
Result:
res6: String = FILLER51
Upvotes: 0
Reputation: 36250
Instead of testing for != upper, test for explicitly lower:
"filler51".map {x => x match {case x if x == x.toUpper && !(x.isDigit) => "_" + x; case x if x == x.toLower => x.toUpper}}.mkString
Upvotes: 0
Reputation: 22449
You're almost there – just need a catch-all to cover all cases, as your two match cases have not exhausted all possibilities (namely, the case of isDigit):
"thisFiller51".map { x => x match {
case x if x == x.toUpper && !x.isDigit => "_" + x
case x if x != x.toUpper => x.toUpper
case x => x
} }.mkString
// res1: String = THIS_FILLER51
Upvotes: 1