使用正则表达式在句子中查找第一个单词

时间:2015-06-15 23:32:15

标签: c# regex

我想为以下情况写一个正则表达式:

  1. 我想知道"怎么"在句子中存在然后显示与如何

  2. 相关的内容
  3. 我想知道"帮助"存在于句子中,然后显示与帮助相关的内容

  4. 如果两者都是"怎么"和"帮助"在句子中存在然后找出哪个词首先出现在"帮助" &安培; "如何"在给出的句子中基于该显示各自的内容

  5. 例如,如果句子是"帮助你,但如何" 在这种情况下,内容与“帮助”有关。应该显示,如果句子是"如何帮助你,在这种情况下,内容与应该如何显示有关。

    我写了一个C#代码,

    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");            
        }
    

    但它没有用,有人可以帮我吗? (我已经在这里针对前两个问题提出了一个问题,根据该问题的答案,我编写了上述代码,但它不适用于第三个问题)

1 个答案:

答案 0 :(得分:3)

你可以使用Negative Look Behinds来匹配“how”,只要你背后没有“帮助”,反之亦然。

代码将是这样的:

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";
}

输出:

how
help
help
how