2016-07-26 9 views
0

Missing numbersについては、elseステートメントに進みます。 "The"を入力すると読み込まれますが、2つの数字を入力すると、カウントはまだ0と表示されます。ラベルを移動して変更する代わりにelseステートメントを返します。どうして?Regex Count not working

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); 
     } 

    } 
} 
+0

正確な入力文字列は何ですか? –

+0

The 3 5 ------- – LoLo

+0

'string s = textbox.ToString();'を 'string s = textbox.Text;'に置き換える必要があります。そうでなければ、別の文字列を解析します:) –

答えて

0

これは私がやる方法です。私はこの方法はそれがはるかに読みクリーンかつ簡単だと思う:あなたは正規表現というチューニングする必要がありますので、

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); 
} 

あなたは、その入力文字列についてはあまり言いませんでした。私はあなたが条件間のスペースを期待し、2桁目の後に何も無視すると思います。

1

Regex.Matches.Countが正しく機能します。あなたは

string s = textbox.Text; 
エルス

string s = textbox.ToString(); 

を交換する必要が

、あなたは別の文字列(textboxタイプ文字列)を分析。

また、テキストボックスの値に1つの変数を使用し、必要なときにのみトリムすることができます。