2
\$\begingroup\$

My requirement is to format the input values to a particular format as "##.###/##.###" Example - My input value can have alphabets, alphanumeric, numeric

  1. Expired -- > if alphabet, output as three space
  2. 2 --> only numeric, add "/" + "0" to format as "##.###/##.###"
  3. 3/2 --> "##.###/##.###"
  4. 0.2/3.4 --- "##.###/##.###"

The below code is working and getting expected results. Is there any better way to avoid multiple if conditions

 Dim input As String = KeyValueDictionary.Item(DictionaryKeyNames.input).ToString()
 If Regex.IsMatch(input, "^[a-za-z ]+$") Then
 input = "   "


 ElseIf IsNumeric(input) Then
 input = input + "/" + "0"
 input = String.Join("/", input.Split("/").[Select](Function(s) Decimal.Parse(s).ToString("00.000")))



 ElseIf Regex.IsMatch(input, "^[0-9/.]+$") Then
 input = String.Join("/", input.Split("/").[Select](Function(s) Decimal.Parse(s).ToString("00.000")))
 End If
\$\endgroup\$
1
\$\begingroup\$

You don't need to use Regex for this, and your regex doesn't cover most of cases anyway. You can simply splitting the input and try parse them into decimals. If they contains any invalid inputs then return three spaces (" ") otherwise print it in "00.000/00.000" format.

Function StringFormatting(input As String) As String
    Dim parts = input?.Split("/").Select(
    Function(s)
        Dim val As Decimal
        Return If(Decimal.TryParse(s, val), CType(val, Decimal?), Nothing)
    End Function).ToList()

    If parts Is Nothing OrElse parts.Count > 2 OrElse parts.Any(Function(v) v Is Nothing) Then
        Return "   "
    End If

    Return $"{parts(0):00.000}/{If(parts.Count = 2, parts(1), 0):00.000}"
End Function

Please note that the code above is assuming that the input would be a short text and with just couple of '/' at worst, otherwise I'd suggest to restructure them to check for parts Is Nothing OrElse parts.Count > 2 first before trying to parse them into decimal to prevent unnecessary process.

Test cases:

  • "2" => "02.000/00.000"
  • "3/2" => "03.000/02.000"
  • "0.2/3.4" => "00.200/03.400"
  • Nothing => " "
  • "" => " "
  • " " => " "
  • "Expired" => " "
  • "/2.1" => " "
  • "1/" => " "
  • "2.3.2" => " "
  • "2/3/2021" => " "
  • "3/Expired" => " "
  • "4/12/Expired" => " "
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.