2009-07-02 61 views
0

我想匹配模式:從0或更多空格開始,接着是「ABC」,然後是任何內容。如何在正則表達式中構造這個

所以像" ABC " " ABC111111" "ABC"這樣的東西就會匹配。
但是像" AABC" "SABC"這樣的東西不匹配。

我想:

String Pattern = "^\\s*ABC(.*)"; 

但它不工作。

任何想法?順便說一句,這是用C#編寫的。

+1

你的模式看起來我的權利。你確定它不起作用嗎? – 2009-07-02 17:39:21

+1

是的,該模式對我也有效 - 也許你的C#代碼有錯誤。你也可以發佈代碼嗎? – 2009-07-02 17:40:59

回答

1

\\通常會放入一個文字反斜槓,這可能是您的解決方案失敗的原因。除非你是做一個替代你不需要繞.*

括號除了空格字符[ \t\n\f\r\x0B]或空格,製表符,換行符,換頁,回報和垂直選項卡還\s匹配字符。

我建議:

String Pattern = @"^[ ]*ABC.*$"; 
2

嘗試

string pattern = @"\s*ABC(.*)"; // Using @ makes it easier to read regex. 

我驗證了這個工程上regexpl.com

+0

難道^只是強制從行首開始考試? – 2009-07-02 17:45:35

0

確保您已設置的正則表達式引擎使用單線,而不是多行。

1

我測試了這一點。有用。如果只希望匹配大寫ABC,則可以省略RegexOptions.IgnoreCase。

/// <summary> 
/// Gets the part of the string after ABC 
/// </summary> 
/// <param name="input">Input string</param> 
/// <param name="output">Contains the string after ABC</param> 
/// <returns>true if success, false otherwise</returns> 
public static bool TryGetStringAfterABC(string input, out string output) 
{ 
    output = null; 

    string pattern = "^\\s*ABC(?<rest>.*)"; 

    if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase)) 
    { 
     Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); 
     output = r.Match(input).Result("${rest}"); 
     return true; 
    } 
    else 
     return false; 
} 

調用代碼:

static void Main(string[] args) 
{ 
    string input = Console.ReadLine(); 

    while (input != "Q") 
    { 
     string output; 
     if (MyRegEx.TryGetStringAfterABC(input, out output)) 
      Console.WriteLine("Output: " + output); 
     else 
      Console.WriteLine("No match"); 
     input = Console.ReadLine(); 
    } 
} 
相關問題