2011-06-14 74 views
1

我有這樣的時刻:名稱userInput在當前上下文中不存在。爲什麼?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 

static void Main(string[] args) 
{ 
    Console.WriteLine("Which teams have played? right vs inbetween the two teams"); 
    Match m = Regex.Match("^(?<team1>\.+) vs (?<team2>\.+)$", userInput); 
    if (m.Success) 
    {  
     string team1 = m.Groups["team1"].Value; 
     string team2 = m.Groups["team2"].Value; 
    } 

    Console.WriteLine("What is the score? ");  
    Match m = Regex.Match("^(?<score1>\.+)/(?<score2>\.+)$", userInput); 
    if (m.Success) 
    { 
     int score1 = m.Groups ["score1"].Value; 
     int score2 = m.Groups ["score2"].Value; 
    } 

我上點一個錯誤說:

「無法識別的轉義序列^(?<team1>\.+)

它也不會告訴我這上score1score2行:

「的類型或命名空間名稱Match找不到(是否缺少using指令或程序essembly引用?)」

和:

「這個名字`Regex'不excist在當前的情況下。「

我想要做的是從一行讀取兩個答案,並將其作爲兩個答案閱讀。

例如:藍隊vs紅隊。

也想爲樂譜做同樣的事情。例如:1/1我知道斜線有點奇怪,但我只是用純粹的懶惰來想出其他的東西。

然後在路徑上,我想將它分配到xy表中。像這樣:http://pastebin.com/ahgP04bU

+1

使用@:var userInput = string.Empty;

  • 如果字符串在其中(如\)有特殊字符,你可以使用@ :'@「^(? \。+)vs ... $」' – 2011-06-14 20:36:54

  • 回答

    4

    通過將變量放在{ ... }中,您將創建一個單獨的塊範圍與這些變量。它們不在這個範圍之外。

    不要這樣做。

    Regex類位於System.Text.RegularExpressions命名空間中;您需要使用using語句包含該名稱空間。

    2

    你還必須包括

    using System.Text.RegularExpressions 
    
    爲了使用正則表達式

    沒有完全限定。

    編輯:有很多,這也會改善你的代碼。當您在if塊內定義變量時,這些變量將在本地限定爲if塊,並在if塊完成後立即進行垃圾回收。

    此外,我沒有看到userInput在代碼中的任何位置定義的位置。

    0
    • 您需要確定命名空間的範圍,大括號({ })當前缺少。
    • 您需要using System.Text.RegularExpressions在其他文件的頂部。
    • userInput不存在,你需要聲明它:你的正則表達式的字符串前@"\myString"
    +0

    在你的第三條語句中說:var userInput = string.empty;字符串不包含空的定義 – deltu 2011-06-14 21:35:47

    +0

    @deltu:道歉。一個錯字 - 「空」應該已被大寫;我已更新。 – 2011-06-14 21:42:34

    +0

    @deltu:雖然,你不想太過於字面意思:字符串需要有一個有意義的值,它需要聲明_and_設置。 – 2011-06-14 21:52:33

    相關問題