Reputation: 89
It keeps going to the else statement for Missing numbers. It reads if I input "The" but when i input two numbers it says the count is still 0
. then will return the else statement instead of going and changing the labels. Why?
protected void submit_Click(object sender, EventArgs e)
{
string input = textbox.Text;
string s = textbox.ToString();
input = input.Trim();
MatchCollection matches = Regex.Matches(s, @"\d+");
string[] result = matches.Cast<Match>()
.Take(2)
.Select(match => match.Value)
.ToArray();
if (input.StartsWith("The") || input.StartsWith("the"))
{
if (matches.Count == 2)
{
alarm.Text = result[0];
server.Text = result[1];
}
else
{
string script = "alert(\"Missing Number(s)!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
}
Upvotes: 1
Views: 327
Reputation: 7880
This is how I would do it. I think this way it's much more cleaner and easier to read:
string input = textbox.Text.Trim();
var match = Regex.Match(input, @"^[tT]he\s(\d+)\s(\d+)\b");
if (match.Success && match.Groups.Count == 3)
{
var alarm = match.Groups[1].Value;
var server = match.Groups[2].Value;
}
else
{
string script = "alert(\"Missing Number(s)!\");"; // Or "invalid format".
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
You didn't say much about that input string, so you may have to tune that regular expression. I supposed you expect spaces between the terms and ignore anything after the second digit.
Upvotes: 0
Reputation: 626794
Regex.Matches.Count
works correctly.
You need to replace
string s = textbox.ToString();
with
string s = textbox.Text;
Else, you analyze a different string (the textbox
type string).
Also, you can use just one variable for the text box value and trim it when necessary only.
Upvotes: 2