首页 > 解决方案 > 查找句子中的单词组合

问题描述

我正在尝试构建一个正则表达式模式,使我能够检查一个特定的单词组合是否出现在一个句子中。

文本示例

在您的问题正文中,首先扩展您在标题中的摘要。解释你是如何遇到你试图解决的问题的,以及任何阻碍你自己解决的困难。您问题的第一段是大多数读者会看到的第二件事,因此请使其尽可能引人入胜且内容丰富。

现在我正在尝试创建一个模式,它会告诉我此文本中的任何句子是否包含任何顺序的单词组合。

Example combination:
summary, question

示例代码:

        Regex regex = new Regex(@"(summary|question).*\w\.");
        Match match = regex.Match("In the body of your question, start by expanding on the summary you put in the title. Explain how you encountered the problem you're trying to solve, and any difficulties that have prevented you from solving it yourself. The first paragraph in your question is the second thing most readers will see, so make it as engaging and informative as possible.");
        if (match.Success)
        {
            Console.WriteLine("Success");
        } else {
            Console.WRiteLine("Fail");
        }

输出:

Success

示例代码:

Regex regex = new Regex(@"(summary|question).*\w\.");
            Match match = regex.Match("Explain how you encountered the problem you're trying to solve, and any difficulties that have prevented you from solving it yourself. The first paragraph in your question is the second thing most readers will see, so make it as engaging and informative as possible.");
            if (match.Success)
            {
                Console.WriteLine("Success");
            } else {
                Console.WRiteLine("Fail");
            }

输出:

Fail

我的最终目标是从用户(1..n)读取任意数量的单词,将它们构造成正则表达式模式字符串并使用该模式来检查任何文本。

例如(请忽略我只是使用视觉表示的错误模式)

Words: question, summary    
pattern: (question|summary).*\w  
Words: user, new, start    
pattern: (user|new|start).*\w

我真的希望这是有道理的。我正在重新学习正则表达式(十多年来没有使用过它)。

编辑 1(重新打开理由):

我已经回顾了之前完成的一些答案,并且更接近了。

我的新模式如下:

/^(?=.*Reference)(?=.*Cheatsheet)(?=.*Help).*[\..]/gmi

但是按照这里的示例https://regex101.com/r/m2HSVq/1它不能完全工作。它在整个段落中寻找单词组合,而不是句子。

根据原始文本,我只想在句子内返回匹配项(由句号或文本结尾分隔)。

我的后备选项是在句号处拆分字符串,然后在我找不到解决方案时进行单独匹配。

标签: c#regex

解决方案


推荐阅读