2013-04-12 39 views
1

我需要簡單地看看是否有任何匹配的文件名中的一組特殊字符我已經嘗試過所有常見的正則表達式,包括下面的那些。所有這些例子都會找到除括號外的任何特殊字符。C#在文件名中找到特殊字符

Regex.Match(filename, "[\\[\\]{}[email protected]#]"); 
// I even separated this out into 3 like this 
Regex.Match(filename, "["); 
Regex.Match(filename, "]"); 
Regex.Match(filename, "[{}[email protected]#]"); 

filename.IndexOfAny("[]{}[email protected]#".ToCharArray()) != -1 

什麼給了?

+0

當你說特殊字符時,你是什麼意思?是什麼讓他們對你的用例「特殊」? – Oded

+0

方括號專門打破我們的系統,所以我們不能允許上載括號的文件。 –

+0

「括號」,你的意思是方形的[和]? ({}被一些人稱爲花括號。) –

回答

4
Regex.Match(test, @"[\[\]{}[email protected]#]"); 

工作對我來說:

string test = "aoeu[aoeu"; 

Match m = Regex.Match(test, @"[\[\]{}[email protected]#]"); 
// m.Success == true 
+0

這解決了我的支架問題,但我怎麼能把一個雙引號」成要檢查的字符串文字? –

+0

加倍:'@「[\ [\]'〜#%&* {} <>:?/ | \\ @!」「]」' –

+1

@TimeTravelMishap,加倍。 「@」符號表示[逐字字符串文字]的開頭(http://msdn.microsoft.com/zh-cn/library/vstudio/362314fe.aspx) – Travis

1

您的解決方案

filename.IndexOfAny("[]{}[email protected]#".ToCharArray()) != -1 

是完美的了。將正則表達式轉義給Houdini。