1

Correct input format: xxxx/yyyy/zzzz i.e. 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))
6
  • And if it contains leading zeros already? How about "0001/0100/0123/"? But "01/100/123" is invalid? How many leading zeros should be added, if we have 2 substrings? Commented Mar 19, 2018 at 20:10
  • "0001/0100/0123/" is good, we don't have to do anything else. While for "01/100/123", it'd need to be padded to "0001/0100/0123/". Final count should be 12 when parts are added. At least there will be 2 parts, ideally 3, and no more. Commented Mar 19, 2018 at 20:19
  • But "//" cant be filled to "0000/0000/0000" or "/" to "000000/000000"? Commented Mar 19, 2018 at 20:28
  • We'd ignore such cases, they don't provide any value to downstream. Commented Mar 19, 2018 at 20:33
  • 1
    You should provide two lists, one with all matching, one with all failing expressions and a method, to map over. Commented Mar 19, 2018 at 21:26

1 Answer 1

2

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

returns 2345/1234/1234, 0012/2345/0003 for input 12345/1234/1234, 012/12345/3 but should return invalid, invalid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.