2011-08-22 162 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 
相关问题