0

Lets say i have string like this Test%Test and i have stored strings like this:

Test123Test TestTTTTest Test153jhdsTest 123Test TEST123

So what i want is when i type in textbox Test it would filter me everything with Test in itselft and that will get me all strings which is easy, but i want to type in Test%Test and it needs to filter me everything that has Test[anything]Test in itself (so result would be first, second and third string). How can i do it?

Parpil
  • 63
  • 10
  • 1
    http://stackoverflow.com/questions/5417070/c-sharp-version-of-sql-like link can help you. – mfatih Jan 02 '17 at 16:32
  • 1
    There is probably a good regex for it. But I'm by no means a regex expert. So I would solve it with String.StartsWith and String.EndsWith. So spiltting the seach term on '%' and than using to two values – ErazerBrecht Jan 02 '17 at 16:33
  • What is the role of the `%` character here? Is it some sort of wildcard? A separator? Or is it a literal "%"? – heltonbiker Jan 02 '17 at 16:57

1 Answers1

3

a simple solution using a regex is:

string[] values = new string[] { "Test123Test",
            "TestTTTTest",
            "Test153jhdsTest",
            "123Test",
            "TEST123" };

string searchQuery = "Test%Test";

string regex = Regex.Escape(searchQuery).Replace("%", ".*?");

string[] filteredValues = values.Where(str => Regex.IsMatch(str, regex)).ToArray();

Or for a single match:

string value = "Test123Test";

string searchQuery = "Test%Test";

string regex = Regex.Escape(searchQuery).Replace("%", ".*?");

if ( Regex.IsMatch(value, regex) )
{
    // do something with the match...                
}

We replace % with a regular expression (. = any character, * = zero or more times, ? = lazy quantifier). You can learn more about regular expressions here

Sjors Ottjes
  • 1,067
  • 2
  • 12
  • 17