正确的输入格式:xxxx / yyyy / zzzz,即每个部分有4个字符。 字符串的总长度(不包括“/”)应始终为12。
输入可以是:xxx / yyy / zzz然后它应该填充为0xxx / 0yyy / 0zzz
在这个阶段,至少有一个“/”将在那里。如果有2个部分,那么我们需要6个字符。
在Scala中寻找带填充逻辑的正则表达式。
// line to tune:
val matchThis = raw"(\d{4})/(\d{4})/(\d{4})".r
val valids = List ("1/6", "123456/1", "1/123456", "123456/123456", "1/2/3", "1234/1234/1234", "012/12/3", "1/01/012")
val invalids = List ("/6", "1234567/1", "1/1234567", "1234567/1234567", "/2/3", "1/2/", "12345/1234/1234", "012/12345/3", "1/01/012345")
def tester (input: String) = {
input match {
case matchThis(_*) => "It's valid!"
case _ => "Need some work" /*???*/
}
}
valids.map (s => tester(s))
invalids.map (s => tester(s))
答案 0 :(得分:2)
这不是防弹的,但我认为它涵盖了你所描述的大部分内容。
val valid = raw"(\d{1,6})/(\d{1,6})(?:/(\d{1,4}))?".r
val output = input match {
case valid(a,b,null) => f"$a%6s/$b%6s" replaceAll(" ","0")
case valid(a,b,c) => f"$a%4s/$b%4s/$c%4s" replaceAll(" ","0")
case _ => "invalid"
}
稍微完整一点。
val valid = raw"(\d{1,4})/(\d{1,4})/(\d{1,4})|(\d{1,6})/(\d{1,6})".r
val output = input match {
case valid(null,null,null,a,b) => f"$a%6s/$b%6s" replaceAll(" ","0")
case valid(a,b,c,null,null) => f"$a%4s/$b%4s/$c%4s" replaceAll(" ","0")
case _ => "invalid"
}