scala..如何检查字符上的非数字
我需要这样做一个字符转换:scala..如何检查字符上的非数字,scala,digit,Scala,Digit,我需要这样做一个字符转换: accountNumber=>ACCOUNT\u编号 如果有大写字母,则前缀为下划线。如果不是,只需将字符大写即可 我试着像下面一样 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
accountNumber=>ACCOUNT\u编号
如果有大写字母,则前缀为下划线。如果不是,只需将字符大写即可
我试着像下面一样
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
它可以工作,但当中间有一个数字时,它的工作方式就不同了
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
我希望它能打印FILLER51。为此,我对代码进行了如下调整,但出现了一个错误
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
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(属于java.lang.Character类)
at.$line40$$read$$$anonfun$1(:12)
at.$line40$$read$$$anonfun$1$adapted(:12)
在$$Lambda$1399/645018917。应用(未知来源)
美联社(StringOps.scala:29)
... 28删去
请使用以下方法
scala> "filler51".map(x=>if(x>='A' && x<='Z') '_'.toString+x.toString else x.toString)
.mkString
.toUpperCase
您就快到了–只需要一个包罗万象的方法来涵盖所有案例,因为您的两个比赛案例还没有用尽所有的可能性(即isDigit案例):
而不是测试!=上限,测试下限:
"filler51".map {x => x match {case x if x == x.toUpper && !(x.isDigit) => "_" + x; case x if x == x.toLower => x.toUpper}}.mkString
我希望这对你有帮助!好啊但是,在我的代码中否定isDigit语法有什么错呢?如果您希望它能够处理所有Unicode小写/大写,最好不要使用与A和Z的显式比较。。但是在我的代码中否定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
"filler51".map {x => x match {case x if x == x.toUpper && !(x.isDigit) => "_" + x; case x if x == x.toLower => x.toUpper}}.mkString