ClanKiller.com
https://forums.clankiller.com/

An easy c# search parsing method
https://forums.clankiller.com/viewtopic.php?f=24&t=2243
Page 1 of 1

Author:  Satis [ Wed Mar 07, 2007 7:39 am ]
Post subject:  An easy c# search parsing method

I wrote this recently to help parse some search text. It's nothing crazily difficult, but basically looks for single and double quotes and breaks the search on it based up. for example, if you search for

this "is a test"

it'll search

WHERE whatever like '%this%' AND whatever like '%is a test%'

I thought I'd share since it's one of the few things I've managed to accomplish lately in the sea of problems I've been swimming in. It converts all single quotes to double quotes, so don't try mixing and matching quotes.

[php]
string where = null;
int i = 0;

//turn single quotes into double quotes
enteredsearch = Regex.Replace(enteredsearch, "[']", "\"");
int loopcontrol = 0;
while (enteredsearch.Contains("\""))
{
//find the first quote
int start_index = enteredsearch.IndexOf("\"");
//find the second quote
int end_index = enteredsearch.IndexOf("\"", start_index + 1);
if (end_index == -1)
{
//if no second quote abort
break;
}
else
{
//get substring
string inside = enteredsearch.Substring(start_index + 1, (end_index - start_index - 1));
if (i > 0)
{
where += " AND";
}
where += " (Question like '%" + inside + "%' OR Answer like '%" + inside + "%')";
//remove quoted section from original query -
//this has the added benefit of replacing identical quoted sections
enteredsearch = enteredsearch.Replace("\"" + inside + "\"", string.Empty);
i++;
}
loopcontrol++;
if (loopcontrol > 10)
{
//we've looped 10 times... this is excessive, so abort the loop
break;
}
}

//take remaining words and add them to the search
if (enteredsearch.Trim().Length > 0)
{
string[] words = enteredsearch.Trim().Split(' ');
for (int k = 0; k < words.Length; k++)
{
if (i > 0 || k > 0)
{
where += " AND";
}
where += " (Question like '%" + words[k] + "%' OR Answer like '%" + words[k] + "%')";
}
}
[/php]

Page 1 of 1 All times are UTC - 6 hours
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/