【问题标题】:C# Regex to match the keyword in TEXT and get few words around the matchC# Regex 匹配 TEXT 中的关键字并在匹配项周围获取几个单词
【发布时间】:2016-03-03 21:22:08
【问题描述】:

我需要匹配文本并获取匹配的单词。

例如,我的文本是 HTML 格式,我将在下面用作示例

<p>Do not forget the error handling, I don't exactly know what happens if it wants to replace an occurence and can't find it</p>
<p>Edit: If you have multiple entries which should be replaced, loop the replace part until it will not be able to replace anymore then it will throw an error you can catch to continue</p>

匹配案例:

案例1(如果中间有匹配词):occurence

结果:I don't exactly know what happens if it wants to replace an occurence and can't find it

案例2(如果第一个单词中的单词匹配):Do not

结果:Do not forget the error handling, I don't exactly know what happens if it wants to replace an occurence and can't find it

案例3(如果匹配文本中最后一个单词):to continue

结果:If you have multiple entries which should be replaced, loop the replace part until it will not be able to replace anymore then it will throw an error you can catch to continue

如果它是文本之间的单词,它应该在单词周围显示文本。 如果匹配词是第一个词,那么它应该从第一个词本身获取文本

如果匹配是最后一个单词,则从匹配的最后一个单词之前获取文本。

正则表达式(?&lt;=(\w+)\s)?(continue)(?=\s(\w+))?

它只匹配单词我怎样才能让我们在匹配的关键字周围说 10 -15 个单词。

这可以使用正则表达式吗

【问题讨论】:

  • 您的问题不清楚。请重新考虑文本案例。怎么可能在一个测试用例中,关键字前面恰好需要 12 次重复,而在另一种测试用例中,您需要超过 15 次?

标签: c# regex


【解决方案1】:

案例一:

([\w\s']+(?:occurence)[^<]+)|>((?:occurence)[^<]+)|[^>]+(?:occurence)<

Regex Demo

输出:

我不知道如果它想替换某个事件会发生什么 却找不到

案例 2:

([\w\s']+(?:Do not)[^<]+)|>((?:Do not)[^<]+)|[^>]+(?:Do not)<

[Regex Demo]

输出:

不要忘记错误处理,我不知道如果 它想替换一个出现但找不到它

案例 3:

([\w\s']+(?:to continue)[^<]+)|>((?:to continue)[^<]+)|[^>]+(?:to continue)<

Regex Demo

输出:

编辑:如果您有多个条目需要替换,请循环 更换零件,直到它不能再更换,然后它会 抛出一个你可以捕捉到的错误以继续

限制字数:

案例一:

>(Do not(?:\s(?:[\w']+),?){0,100})|((?:\s(?:[\w']+)){0,100}\s?Do not(?:\s(?:[\w']+),?){0,100})|((?:\s(?:[\w',]+)){0,100}\s?Do not)<

Regex Demo

案例 2:

>(occurence(?:\s(?:[\w']+),?){0,100})|((?:\s(?:[\w']+)){0,100}\s?occurence(?:\s(?:[\w']+),?){0,100})|((?:\s(?:[\w',]+)){0,100}\s?occurence)<

Regex Demo

案例 3:

>(continue(?:\s(?:[\w']+),?){0,100})|((?:\s(?:[\w']+)){0,100}\s?continue(?:\s(?:[\w']+),?){0,100})|((?:\s(?:[\w',]+)){0,100}\s?continue)<

Regex Demo

【讨论】:

  • 还有一个问题,你在哪里指定了要检索的单词数,因为我在上面的正则表达式中看不到......
  • 已编辑:此处的字数{0,100}
猜你喜欢
  • 1970-01-01
  • 2011-09-01
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多