简体   繁体   中英

Finding a first word in sentence using Regular expression

I want to write a regular expression for following situation:

  1. I want to find out if the word "how" exists in the sentence then show the content related to how

  2. I want to find out if the word "help" exists in the sentence then show the content related to help

  3. If both "how" and "help" exist in the sentence then find out which word occurred first from "Help" & "How" in the sentence given & based on that display respective content

For Example if the sentence is like "Help you, but how" in this case content related to 'help' should display and if the sentence is "how to help you", in this case content related to how should be displayed.

I wrote a C# code like,

if (((Regex.Match(sentence, @"(\s|^)how(\s|$)").Success) && 
     (Regex.Match(sentence, @"(\s|^)help(\s|$)").Success)) || 
     Regex.IsMatch(sentence, @"(\s|^)how(\s|$)", RegexOptions.IgnoreCase))
    {
        Messegebox.show("how");
    }
    else if (Regex.IsMatch(sentence, @"(\s|^)help(\s|$)", RegexOptions.IgnoreCase))
    {
        Messegebox.show("help");            
    }

But it is not working, can anyone help me please in this ? (I have already raised a question for first 2 issue here and based on the answers in that question I wrote the above code but it is not working with the 3rd issue)

You can use Negative Look Behinds so you match "how", just if you don't have a "help" behind it, and vice-versa.

The code would be something like this:

static Regex how = new Regex(@"(?<!\bhelp\b.*)\bhow\b", RegexOptions.IgnoreCase);
static Regex help = new Regex(@"(?<!\bhow\b.*)\bhelp\b", RegexOptions.IgnoreCase);

static void Main(String[] args)
{
    Console.WriteLine(helpOrHow("how"));
    Console.WriteLine(helpOrHow("help"));
    Console.WriteLine(helpOrHow("Help you how"));
    Console.WriteLine(helpOrHow("how to help you"));
}

static string helpOrHow(String text)
{
    if (how.IsMatch(text))
    {
        return "how";
    }
    else if (help.IsMatch(text))
    {
        return "help";
    }
    return "none";
}

Output:

how
help
help
how

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM