简体   繁体   中英

Regex scala: Format matching and padding

Correct input format: xxxx/yyyy/zzzz ie 4 chars for each part. Total length of the string (not counting "/") should always be 12.

Input can be: xxx/yyy/zzz then it should be padded to come out as 0xxx/0yyy/0zzz

At this stage at least one "/" will be there. If there are 2 parts then we need 6 chars for both.

Looking for a regex with padding logic in 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))

This isn't bulletproof but I think it covers most of what you've described.

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"
}

A little more complete.

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM