Reputation:
I'm trying to figure out, how to find equal sub-string in big list of strings.
This method works fine:
var results = myList.FindAll(delegate (string s) { return s.Contains(myString); });
But it also looks for sub-string with part of word, for example, if I'm looking for "you do" it founds also extra "you dont" because contains "you do.."
In case of string, this method seems gives desired result:
bool b = str.Contains(myString);
if (b)
{
int index = str.IndexOf(myString);
}
How to get same kind of matching with list
Upvotes: 1
Views: 559
Reputation: 38767
You could use regular expressions to return all of the matches for a set of potential terms:
string[] stringsToTest = new [] { "you do", "what" };
var escapedStrings = stringsToTest.Select(s => Regex.Escape(s)); // escape the test strings so that we can safely build them into the expression
var regex = new Regex("\\b(" + string.Join("|", escapedStrings) + ")\\b");
var matches = regex.Matches("How you do? How you don't? What you do? How you do what you do?");
If you only have one term you can rewrite this as:
var regex = new Regex(string.Format("\\b({0})\\b", Regex.Escape("you do")));
var matches = regex.Matches("How you do? How you don't? What you do? How you do what you do?");
And then you can match use match.Groups[0]
(for each group in the match collection) to get the matched value:
foreach (Match m in matches)
{
Console.WriteLine(string.Format("Matched {0} at {1}", m.Groups[0].Value, m.Groups[0].Index));
}
Upvotes: 1