C# grammar and switch wildcard

2349 views c#
8

I would like to add, that whenever it recognizes 'search X' it is going to search for 'X', but i don't know how i have to add that to the grammar, or how to do such a thing with my switch statement.

private void Form1_Load(object sender, EventArgs e)
{
    Choices commands = new Choices();
    commands.Add(new string[] { "hello", "start chrome", "search" });
    GrammarBuilder gBuilder = new GrammarBuilder();
    gBuilder.Append(commands);
    gBuilder.Culture = new System.Globalization.CultureInfo("en-GB");
    Grammar grammar = new Grammar(gBuilder);

    recEngine.LoadGrammarAsync(grammar);
    recEngine.SetInputToDefaultAudioDevice();
    recEngine.SpeechRecognized += RecEngine_SpeechRecognized;
}

private void RecEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
    switch (e.Result.Text)
    {
        case "hello":
            synthesizer.SpeakAsync("Hello! How are you doing today?");
            break;
        case "start chrome":
            Process.Start("http://www.google.com");
            break;
        case "search":
            SearchChrome("search");
            break;
    }
}

static void SearchChrome(string searchterm)
{
    Process.Start("https://www.google.com/search?q=" + searchterm);
}

So i'd like to add to my grammar "Search X", and to my cases "Search X", with it searching for whatever X is.

Thanks in advance!

answered question

Fastest solution is to make an delay to say X and wait for user to say X and then concatenate it with Search. User Says Search; he will wait a second and then says X. You have activated Search Command and then you will search for X. Or you can remove switch and use IF statement to check whether the input is begin with Search or not. if it does, you can split the string to get Search Phrase.

Since it is difficult to know how long is the best to wait and you might be error prone with any value that you choose, why not two use two different keywords for each case?

1 Answer

6

switch doesn't work with wildcards, it doesn't even accept variable in case statements. For this you will have to use the classical "if" with a regex expression:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        Regex recognizeText = new Regex(@"search (?<criteria>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        string input = "search blabla zsdfsdf";

        var match = recognizeText.Match(input);
        if (match.Success)
        {
            var searchCriteria = match.Groups["criteria"];
            Console.WriteLine(searchCriteria.Value);
        }
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.