我想在包含任何內容但不包含「僅空格」的情況下匹配字符串。如何使用.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
謝謝
嗨丹尼爾。如果可能的話,我想在這裏使用正則表達式,因爲我使用正則表達式進行其他驗證,而不僅僅是空間問題。 – nuxibyte 2013-02-12 13:50:50
@errolc:你真的需要字符串的值作爲'match.Value'的一部分嗎?或者,你對'match.Sheccess'是'true'感興趣嗎? – 2013-02-12 14:00:56
我只想知道它是否匹配。我不在乎它的價值。我正在使用它驗證一個字符串。或者根據正則表達式「validator」有效......在這種情況下,繼續或者不是,barf並退出。 – nuxibyte 2013-02-12 14:04:44