2013-02-12 18 views
4

我想在包含任何內容但不包含「僅空格」的情況下匹配字符串。如何使用.Net正則表達式匹配除'空格'以外的任何內容

空間很好,只要還有別的東西,它可以在任何地方。

當空間出現在任何地方時,我似乎無法獲得匹配。

(編輯:我要做到這一點的正則表達式,我最終想將它與使用其他正則表達式模式相結合|)

這裏是我的測試代碼:

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<string> strings = new List<string>() { "123", "1 3", "12 ", "1 " , " 3", " "}; 

     string r = "^[^ ]{3}$"; 
     foreach (string s in strings) 
     { 
      Match match = new Regex(r).Match(s); 
      Console.WriteLine(string.Format("string='{0}', regex='{1}', match='{2}'", s, r, match.Value)); 
     } 
     Console.Read(); 
    } 
} 

哪個給出了這樣的輸出:

string='123', regex='^[^ ]{3}$', match='123' 
string='1 3', regex='^[^ ]{3}$', match='' 
string='12 ', regex='^[^ ]{3}$', match='' 
string='1 ', regex='^[^ ]{3}$', match='' 
string=' 3', regex='^[^ ]{3}$', match='' 
string=' ', regex='^[^ ]{3}$', match='' 

我想是這樣的:

string='123', regex='^[^ ]{3}$', match='123' << VALID 
string='1 3', regex='^[^ ]{3}$', match='1 3' << VALID 
string='12 ', regex='^[^ ]{3}$', match='12 ' << VALID 
string='1 ', regex='^[^ ]{3}$', match='1 ' << VALID 
string=' 3', regex='^[^ ]{3}$', match=' 3' << VALID 
string=' ', regex='^[^ ]{3}$', match='' << NOT VALID 

謝謝

回答

6

這裏不需要正則表達式。您可以使用string.IsNullOrWhitespace()

正則表達式是這樣的:

[^ ] 

這裏做的事情很簡單:它檢查,如果你的字符串包含任何不是一個空格。

我調整你的代碼中加入match.Success到輸出略有:

var strings = new List<string> { "123", "1 3", "12 ", "1 " , " 3", " ", "" }; 

string r = "[^ ]"; 
foreach (string s in strings) 
{ 
    Match match = new Regex(r).Match(s); 
    Console.WriteLine(string.Format("string='{0}', regex='{1}', match='{2}', " + 
            "is match={3}", s, r, match.Value, 
            match.Success)); 
} 

結果將是:

string='123', regex='[^ ]', match='1', is match=True 
string='1 3', regex='[^ ]', match='1', is match=True 
string='12 ', regex='[^ ]', match='1', is match=True 
string='1 ', regex='[^ ]', match='1', is match=True 
string=' 3', regex='[^ ]', match='3', is match=True 
string=' ', regex='[^ ]', match='', is match=False 
string='', regex='[^ ]', match='', is match=False 

BTW:與其new Regex(r).Match(s)你應該使用Regex.Match(s, r)。這允許正則表達式引擎緩存模式。

+0

嗨丹尼爾。如果可能的話,我想在這裏使用正則表達式,因爲我使用正則表達式進行其他驗證,而不僅僅是空間問題。 – nuxibyte 2013-02-12 13:50:50

+0

@errolc:你真的需要字符串的值作爲'match.Value'的一部分嗎?或者,你對'match.Sheccess'是'true'感興趣嗎? – 2013-02-12 14:00:56

+0

我只想知道它是否匹配。我不在乎它的價值。我正在使用它驗證一個字符串。或者根據正則表達式「validator」有效......在這種情況下,繼續或者不是,barf並退出。 – nuxibyte 2013-02-12 14:04:44

0

如何使用^\s+$並簡單地否定Match()的結果?

+0

'IsMatch()'也可以使用。 – nhahtdh 2013-02-12 14:08:03

+0

感謝你們兩位。我需要更多地關注Regex課堂。 – nuxibyte 2013-02-12 14:29:44

6

我會使用

^\s*\S+.*?$ 

打破正則表達式...

  • ^ - 線
  • 開始
  • \s* - 零個或多個空白字符
  • \S+ - 一個或更多非空白字符
  • .*? - 任何字符(空白或不 - 非貪婪 - >儘可能少匹配)
  • $ - 行結束。
+0

有趣的,謝謝@Grhm!它似乎不允許換行字符'\ n',應該在'^'之後立即放置'\ n *'? – 2014-01-10 02:52:35

+1

@伊坎貝爾你可能需要添加一個SingleLine選項來使。字符行軍換行符。請參閱http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions(v=vs.110).aspx – Grhm 2014-01-11 06:54:39

相關問題