2011-08-22 145 views
0

所以現在我使用這個簡單的方法來檢查字符串另一個字符串另一個字符串:搜索字符串包含特殊字符

System.Text.RegularExpressions.Regex.IsMatch(toSearch, toVerifyisPresent, System.Text.RegularExpressions.RegexOptions.IgnoreCase) 

現在,它的大部分工作正常。但是我最大的問題是,如果我試圖尋找「你有+現在」這樣的東西,如果「你有+現在」在那裏,它仍然會回來。我想這是因爲字符串中的「+」。

我能做些什麼來解決這個問題?

+11

出了什麼問題'string.Contains'? – Oded

+0

你的正則表達式是什麼樣的? –

回答

2

根據以上評論Oded

toSearch.toLowerCase().Contains(toVerifyIsPresent.toLowerCase()) 

都轉換爲小寫將提供相同的功能使用IgnoreCase

+0

更好:toSearch.IndexOf(toVerifyIsPresent,StringComparison.OrdinalIgnoreCase)== -1' – Serguei

3

您可以使用\轉義特殊字符。但是Oded指出,如果你只是檢查一個字符串是否包含某些東西,那麼使用String.Contains方法會更好。

特殊字符在正則表達式:

http://www.regular-expressions.info/characters.html

String.Contains方法:

http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

+1

此外,如果您使用'\'來轉義'+',不要忘記用另一個'\'來逃避''''換句話說''areyou \\ + present「'應該這樣做或'@」areyou \ +本「'。 – Serguei

+0

@Serguei,好點。 –

1

在正則表達式+一次或多次匹配前面的組,這樣的正則表達式匹配areyou+present

areyoupresent 
areyouupresent 
areyouuuuuuuuuuuuuuuuuuuuuuuuuuupresent 

等...

1

演示IronPython中:

>>> from System.Text.RegularExpressions import * 
>>> Regex.IsMatch("This is a sentence containing 'areyou+present'", "areyou+present"); 
False 
>>> Regex.IsMatch("This is a sentence containing 'areyou+present'", "areyou\\+present"); 
True 
>>> Regex.IsMatch("This is a sentence containing 'areyou+present'", "areyou[+]present"); 
True 
>>> Regex.IsMatch("This is a sentence containing 'areyou+present'", Regex.Escape("areyou+present")); 
True 
相關問題