在字符串中搜索包含特殊字符的另一个字符串

本文关键字:字符串 另一个 特殊字符 搜索 包含 | 更新日期: 2023-09-27 18:06:17

现在我用这个简单的方法来检查一个字符串是否为另一个字符串

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

现在,大部分工作正常。但我最大的问题是,如果我试图搜索"areyou+present"之类的东西,如果"areyou+present"在那里,它仍然会返回false。我认为这是因为字符串中的"+"。

我能做些什么来解决这个问题?

在字符串中搜索包含特殊字符的另一个字符串

可以使用'转义特殊字符。但是正如Oded指出的,如果你只是检查一个字符串是否包含一些东西,你最好使用String.Contains方法。

regex中的特殊字符:

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

字符串。包含方法:

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

根据Oded的上述评论。

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

将两者转换为小写将提供与使用IgnoreCase

相同的功能

在正则表达式中+匹配前一组一次或多次,因此正则表达式areyou+present匹配:

areyoupresent
areyouupresent
areyouuuuuuuuuuuuuuuuuuuuuuuuuuupresent

等等…

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