2011-03-18 43 views

回答

9

我不知道你的意思到底是什麼,但我猜你要檢查恰好一個空白,但任意數量的非空白字符:

@"^\S*\s\S*$" 

示例代碼:

Regex regex = new Regex(@"^\S*\s\S*$"); 
Console.WriteLine(regex.IsMatch("Hello, world!")); 
Console.WriteLine(regex.IsMatch("This contains three spaces.")); 
Console.WriteLine(regex.IsMatch("Two\nlines.")); 

輸出:

 
True 
False 
True 

其他變化

要檢查字符串中只包含一個空白(無其他字符):

@"^\s$" 

要檢查如果字符串包含至少一個空白:

@"\s" 
+0

對於第二種情況,只有一個空格,'str!= null && str.Le ngth == 1 && Char.IsWhiteSpace(str [1])'可能比正則表達式更高效。 – 2011-03-18 21:24:05

+0

我想你的意思是'char.IsWhiteSpace(str [0])'? – 2011-03-19 10:58:22

+0

Drat。是。爲什麼5分鐘後沒有評論可以修改? – 2011-03-20 16:21:52