简体   繁体   English

正则表达式在特定单词之前和之后找到N(指定数字)单词

[英]Regex to find N (specified number) words before and after a specific word

Can someone help me doing following search using Regex in C# 有人可以帮我在C#中使用Regex进行搜索

I need a regex that will give me specific number of words before and after a specific word that will include the search word itself. 我需要一个正则表达式,它会在包含搜索词本身的特定单词之前和之后给出特定数量的单词。 Please note I want to be able to specify how many words before and after I want. 请注意我希望能够指定我想要之前和之后的单词数量。 If the search word is in the start of the text then it returns just the N number of words after the search word and vice-versa if the search word is in the end of the text. 如果搜索词位于文本的开头,那么它只返回搜索词后面的N个单词,反之亦然,如果搜索词位于文本的末尾。 Also the search should be able to provide multiple matches from the text that I can process. 此外,搜索应该能够从我可以处理的文本中提供多个匹配。

For instance I want to get "2" words around the search word "example" so that will return multiple results in following the multiline text. 例如,我想在搜索词“example”周围得到“2”字,这样就会在多行文字后面返回多个结果。

"example one in this lesson is an example summary that we are using as an example. How many words are in this example? We only want the first few examples." “本课程中的示例一是我们用作示例的示例摘要。此示例中有多少单词?我们只想要前几个示例。”

Returns following results 返回以下结果

"example one in" (note how first search has no first 2 words) “示例一” (注意首次搜索没有前2个单词)

"is an example summary that" “是一个例子摘要”

"as an example. How many" “作为一个例子。有多少”

"in this example? We only" “在这个例子中?我们只是”

Thanks. 谢谢。

given your example the following regex would work 给出你的例子,以下正则表达式将起作用

^example \w+ \w+|\w+ \w+ example[\.\?,]? \w+ \w+

Example C# implementation 示例C#实现

string example = @"example one in this lesson is an example summary that we are using as an example. How many words are in this example? We only want the first few examples.";
string pattern = @"^example \w+ \w+|\w+ \w+ example[\.\?,]? \w+ \w+";

foreach (Match m in Regex.Matches(example, pattern))
{
    Response.Write(m.Value + "<br/>");
}

use a regex debugger (such as debuggex ) or regex tester (such as regexpal ) to do any fine tuning to the above as you try this on additional test cases. 使用正则表达式调试器(如debuggex )或正则表达式测试程序(如regexpal )对上述内容进行任何微调,因为您在其他测试用例中尝试此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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