2013-12-18 38 views
-1

我在c#控制檯應用程序中使用正則表達式,單詞'@'開頭不匹配。 我在我的字符串中以'@'開頭,我使用Regex來匹配那些,但似乎沒有工作。 這是我的代碼如果我放在字邊界 b

public static void regularExpression() 
    { 
     string[] sentences = 
     { 
      "@TODAY is 18 Dec", 
      "@TODAY_CAL is 18 Dex", 
      "@YESTERDAY was 17 dec", 
      "@YESTERDAY_CAL was 17 Dec" 
     }; 

     string sPattern = @"\[email protected]\b"; 

     foreach (string s in sentences) 
     { 
      System.Console.Write("{0,24}", s); 

      if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) 
      { 
       System.Console.WriteLine(" (match for '{0}' found)", sPattern); 
      } 
      else 
      { 
       System.Console.WriteLine(); 
      } 
     } 

    } 

@TODAY不匹配。如果我將sPattern替換爲

string sPattern = @"@TODAY"; 

它有效。但在這種情況下,它甚至匹配@TODAY_CAL,這正是我想要避免的。 我想精確匹配詞。

任何建議???

+1

你嘗試匹配'@ 「@今天\ S」'? – idlerboris

回答

1

試試這個:

string sPattern = @"@TODAY\b";