c# - 使用正则表达式查找句子中的第一个单词

标签 c# regex

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

  1. 我想找出句子中是否存在“how”这个词,然后显示与how相关的内容

  2. 我想找出句子中是否存在“帮助”一词,然后显示与帮助相关的内容

  3. 如果句子中同时存在how和help,则从给定句子中的Help和How中找出哪个词先出现,并根据其显示相应的内容

例如,如果句子是“Help you, but how” 在这种情况下,应显示与“帮助”相关的内容,如果句子是“如何帮助你”,在这种情况下,应显示与“如何”相关的内容。

我写了一段 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");            
    }

但是它不起作用,有人可以帮我解决这个问题吗? (我已经在这里提出了前 2 个问题的问题,并且根据那个问题的答案我写了上面的代码,但它不适用于第 3 个问题)

最佳答案

您可以使用 Negative Look Behinds 来匹配“how”,即使后面没有“help”,反之亦然。

代码应该是这样的:

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

关于c# - 使用正则表达式查找句子中的第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856632/

相关文章:

c# - DataGrid 的自定义列模板

c# - Xamarin Android TextColor 属性在不同设备上表现异常

python - 什么是正则括号的非分组版本

php - 正则表达式:如何不替换任何 html 标签中的特定单词?

用于验证前 n 个字符的正则表达式

c# - 使用 GhostScript 打印 PDF

C# WPF BorderBrush 不会设置颜色

c# - 如何在 C# 中选择 new 和 override?

java - 如何捕获这个带有引号的组?

javascript - 我需要一些有关 javascript 中特定正则表达式的帮助