I'm trying out services in C#, so I cannot debug values using Console.WriteLine(...). That's why I don't know what is in my variable number at the end:
public int addAndSoustractNumberFromAString(string ustr)
{
int result = 0;
if(!string.IsNullOrEmpty(str))
{
string str = ustr.Trim();
//Regexes
System.Text.RegularExpressions.Regex valid_regex = new System.Text.RegularExpressions.Regex(@"[\+]\d+|[\-]\d+");
System.Text.RegularExpressions.Regex invalid_regex = new System.Text.RegularExpressions.Regex(@"[a-zA-Z]");
//Handling errors
if (invalid_regex.IsMatch(str) || !valid_regex.IsMatch(str) || !Char.IsDigit(str[str.Length - 1])) return 0;
if (Char.IsDigit(str[0])) str = "+" + str;
//Load all numbers in a string array
List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());
//Cast string numbers to int + result calculation
foreach (string number in numbers) { if (!int.TryParse(number, out int n)) return 99; result += n; }
}
return result;
}
What does my code? I enter additions & subtractions, it does the operations & return the result as an integer.
example: If I enter "52-2+3" it should return 53
Problem:
My code always returns 99 which means the parsing failed.
Just in case, I tried int.TryParse("-2", out int n) instead and it works fine.
The line that is not working:
List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());
My regexes are fine, I tested them with the website regexstorm net.
My question is, why my string isn't split correctly using a supposed valid regex? Is Regex.Split() not doing what I believe it does? (I thought it would split my string into +number or -number strings
Side note: it's ok if it does not start with a sign. If my string starts with a number it will add "+" at the end for regex purposes.
TryParse? Don't you want to get this value ? Have you tried declaringint n;thenint.TryParse(number, out n)?