ClanKiller.com
http://forums.clankiller.com/

c# method to parse a search string
http://forums.clankiller.com/viewtopic.php?f=24&t=2695
Page 1 of 1

Author:  Satis [ Fri Dec 28, 2007 7:44 am ]
Post subject:  c# method to parse a search string

I wrote this method to take an input "search" and parse out phrases that are surrounded by either double or single quotes. This approximates an "exact match" type of search. I look for double quotes first, remove any double-quoted matches, then reparse for single quote blocks. Anything left over after that is broken up into individual terms on spaces. It returns an ArrayList (basically an array that can dynamically grow).

Code:
    protected ArrayList parseSearchTerms(string searchTerms)
    {
        //parse the query string
        ArrayList exactPhrases = new ArrayList();

        //look for pairs of quotes as 'exact matches'
        string[] stdoubles = searchTerms.Split("\"".ToCharArray());
        if (stdoubles.Length > 1)
        {
            for (int i = 1; i < stdoubles.Length - 1; i = i + 2)
            {
                if (stdoubles[i].Length == 0)
                {
                    continue;
                }
                exactPhrases.Add(stdoubles[i]);
            }
        }
        //now remove them from the original search phrase
        foreach (object item in exactPhrases)
        {
            searchTerms = Regex.Replace(searchTerms, "\"" + item.ToString() + "\"", string.Empty);
        }
        //do the same for single quotes
        string[] stsingles = searchTerms.Split("'".ToCharArray());
        if (stsingles.Length > 1)
        {
            for (int i = 1; i < stsingles.Length - 1; i = i + 2)
            {
                if (stsingles[i].Length == 0)
                {
                    continue;
                }
                exactPhrases.Add(stsingles[i]);
            }
        }
        //now remove them from the original search phrase
        foreach (object item in exactPhrases)
        {
            searchTerms = Regex.Replace(searchTerms, "'" + item.ToString() + "'", string.Empty);
        }

        //take the remaining terms and break them into one-word "phrases"
        string[] st = searchTerms.Split(" ".ToCharArray());
        if (st.Length > 0)
        {
            for (int i = 0; i < st.Length; i++)
            {
                if (st[i].Length == 0 || !Regex.IsMatch(st[i], "[a-zA-Z0-9]"))
                {
                    continue;
                }
                exactPhrases.Add(st[i]);
            }
        }
        return exactPhrases;
    }

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