2011-03-18 87 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