2013-01-25 24 views
0

有一個非常簡單的答案,我知道有這個問題,但我無法理解它 它是一個控制檯應用程序,你輸入一個單詞「密碼」,它會告訴我,是否我的正則表達式匹配,你可以適當地收集正則表達式無法正常工作(無法將字符串轉換爲int(Regex.IsMatch))

基本上我想知道爲什麼這不會工作:

static void Main(string[] args) 
{ 
    Regex regularExpression = new Regex("/^[a-z0-9_-]{3,16}$/"); 

    Console.Write("Enter password: "); 
    string password = Console.ReadLine(); 

    if (Regex.IsMatch(password, regularExpression)) 
     Console.WriteLine("Input matches regular expression"); 
    else 
     Console.WriteLine("Input DOES NOT match regular expression"); 

    Console.ReadKey(); 
} 

我敢肯定,這事做與Regex.IsMatch方法不能將字符串轉換爲int。

+0

**這碼甚至不編譯** - 請解決這一問題和/或張貼的編譯器錯誤。 –

回答

0
Regex regularExpression = new Regex("/^[a-z0-9_-]{3,16}$/"); 

/是符號,將它們替換爲字符串空=>@"^[a-z0-9_-]{3,16}$"

2

因爲使用靜態方法isMatch並給予一個正則表達式的對象,在那裏它應該一個正則表達式的字符串,見Regex class

此外,你不需要.net中的正則表達式分隔符。

使用此:

static void Main(string[] args) { 
    Regex regularExpression = new Regex(@"^[a-z0-9_-]{3,16}$"); 

    Console.Write("Enter password: "); 
    string password = Console.ReadLine(); 

    if (regularExpression.IsMatch(password)) 
     Console.WriteLine("Input matches regular expression"); 
    else 
     Console.WriteLine("Input DOES NOT match regular expression"); 
    Console.ReadKey(); 
} 
相關問題