How can I remove all commas not in brackets from a string in C #?
I have a math analyzer that can do functions like "IntPow (3,2)". If the user inserts "1,000,000" and then adds a plus sign, creating the complete equation "1,000,000 + IntPow (3,2)", the parser fails because it does not work with numbers containing commas.
I need to remove commas from "1,000,000" but not from "IntPow (3,2)" because IntPow has two parameters separated by comma. The final equation will be "1,000,000 + IntPow (3.2)". The equation is stored on one line. How would I remove only the commas that are outside the parentheses? I am assuming and saying that numbers containing commas will not be put into the IntPow parameter list.
When I say "remove commas" I really want to remove "CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator" which can be a comma or a period depending on local. This part will be simple because I am assuming that RegEx will be used and I can just concatenate that value in the RegEx comma.
I have this RegEx: (. *?) For finding parentheses and values inside them, but I'm not sure how to remove only commas outside of RegEx matches.
a source to share
Sub Main()
'
' remove Commas from a string containing expression-like syntax
' (eg. 1,000,000 + IntPow(3,2) - 47 * Greep(9,3,2) $ 5,000.32 )
' should become: 1000000 + IntPow(3,2) - 47 * Greep(9,3,2) $ 5000.32
'
Dim tInput As String = "1,000,000 + IntPow(3,2) - 47 * Greep(9,3,2) $ 5,000.32"
Dim tChar As Char = Nothing
Dim tResult As StringBuilder = New StringBuilder(tInput.Length)
Dim tLevel As Integer = 0
For Each tChar In tInput
Select Case tChar
Case "("
tLevel += 1
tResult.Append(tChar)
Case ")"
tLevel -= 1
tResult.Append(tChar)
Case "," ' Change this to your separator character.
If 0 < tLevel Then
tResult.Append(tChar)
End If
Case Else
tResult.Append(tChar)
End Select
Next
Console.ForegroundColor = ConsoleColor.Cyan
Console.WriteLine(tInput)
Console.WriteLine(String.Empty)
Console.ForegroundColor = ConsoleColor.Yellow
Console.WriteLine(tResult.ToString)
Console.WriteLine()
Console.ResetColor()
Console.WriteLine(" -- PRESS ANY KEY -- ")
Console.ReadKey(True)
End Sub
a source to share
I don't think this is possible with regular expressions. The distinction between inner and outer parentheses is not common language. It is a context insensitive language that cannot be solved using a normal state machine (expression). You need a stack machine (i.e. Something Chad related)
a source to share