My requirement is to format the input values to a particular format as "##.###/##.###" Example - My input value can have alphabets, alphanumeric, numeric
- Expired -- > if alphabet, output as three space
- 2 --> only numeric, add "/" + "0" to format as "##.###/##.###"
- 3/2 --> "##.###/##.###"
- 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
1 Answer 1
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"
=>" "