It is currently Thu Mar 28, 2024 12:40 pm



Reply to topic  [ 1 post ] 
An easy c# search parsing method 
Author Message
Felix Rex
User avatar

Joined: Fri Mar 28, 2003 6:01 pm
Posts: 16646
Location: On a slope
Reply with quote
Post 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]

_________________
They who can give up essential liberty to obtain a little temporary safety, deserve neither liberty nor safety.


Wed Mar 07, 2007 7:39 am
Profile WWW
Display posts from previous:  Sort by  
Reply to topic   [ 1 post ] 

Who is online

Users browsing this forum: No registered users and 7 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by STSoftware.