开发者

search a string for another string that contains a special character

开发者 https://www.devze.com 2023-03-30 12:03 出处:网络
So right now I\'m using this simple method to check a string for another string: System.Text.RegularExpressions.Regex.IsMatch(toSearch, toVerifyisPresent, System.Text.RegularExpressions.RegexOptions.

So right now I'm using this simple method to check a string for another string:

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

Now, its working fine for the most part. But my biggest issue is that if I try to search for something like "areyou+present", if "areyou+present开发者_开发知识库" IS there, it will still come back false. I'm thinking its because of the "+" in the string.

What can I do to work around this?


You can escape special characters using a \. But as Oded points out if you are just checking to see if a string contains something you are better off using the String.Contains method.

Special Characters in regex:

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

String.Contains method:

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


Based on the comment above by Oded.

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

Converting both to lowercase will provide the same functionality as using IgnoreCase


In regular expressions + matches the previous group one or more times so the regex areyou+present matches:

areyoupresent
areyouupresent
areyouuuuuuuuuuuuuuuuuuuuuuuuuuupresent

etc...


Demo in 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
0

精彩评论

暂无评论...
验证码 换一张
取 消