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
Heslacher
50.9k5 gold badges83 silver badges177 bronze badges
asked Apr 30, 2021 at 13:29
\$\endgroup\$

1 Answer 1

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" => " "
answered May 1, 2021 at 3:57
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.