【问题标题】:how to a number of occurrences in a string that begin with a specific word and end with another word [duplicate]如何在以特定单词开头并以另一个单词结尾的字符串中出现多次[重复]
【发布时间】:2018-08-23 19:43:24
【问题描述】:

鉴于我有以下信息:

string Sentence = "The dog jumped over the cat and the cat jumped above the mouse."
string startword = "jumped"
string endword = "the"

我的要求是如何在 C# 中编程以计算句子包含 startword 开头直到匹配第二个 endword 的出现次数。

上面的例子应该返回 2 因为The dog [jumped] ... [the] cat and ...cat [jumped] .. [the] mouse.

我的一个想法是做字符串。将句子分成单词字符串并循环遍历单词并与startword进行比较。如果startword 匹配,则将下一个单词与endword 进行比较,直到找到或句子结束。如果找到了startwordendword,则增加计数器,然后继续搜索startwordendword,直到句子结束。

任何其他建议或代码示例将不胜感激。

【问题讨论】:

  • 请把你的想法变成代码。这会有所帮助。然后你可以检查你的确切位置。

标签: c# regex string split console-application


【解决方案1】:

注意:这里的答案很好,

但是,我只是想 id 指出您可能希望通过使用 \b 来尊重单词边界。否则你可能会选择部分单词

\b 匹配任何单词边界。具体来说,\w\W

var regex = new Regex(@"\bjumped\b.*?\bthe\b");
var str = "The dog jumped over theatre cat and the cat bejumped above the mouse.";
var matches = regex.Matches(str);
Console.WriteLine("Count : " + matches.Count);
foreach (var match in matches)
{
   Console.WriteLine(match);
}

You can see the demo here

【讨论】:

  • 我认为你对我问题的回答是最好的迈克尔。这正是我正在寻找的。非常感谢!
  • @Andy 如果这对你有帮助,别忘了标记它并标记它已回答,干杯
【解决方案2】:
regexPattern= "jumped[\s\w]+?the"
searchText = "The dog jumped over the cat and the cat jumped above the mouse."

上述正则表达式符合您的问题。 要计算出现次数,请使用

regexCount = Regex.Matches(searchText, regexPattern).Count

【讨论】:

    【解决方案3】:

    我建议为此使用正则表达式。

    使用的正则表达式非常简单:jumped.*?the

    你可以在这里玩:https://regex101.com/r/h0MKyV/1

    由于您期望多个匹配项,您可以在 C# 中使用 regex.Matches 调用来获取它们。所以你的代码应该如下所示:

    var regex = new Regex("jumped.*?the");
    var str = "The dog jumped over the cat and the cat jumped above the mouse.";
    var matches = regex.Matches(str);
    

    您可以遍历 matches 以访问每个匹配项,或直接获取其计数。

    【讨论】:

    • 非常感谢。我只需要计数。我看到了其他 Regex 示例,但我不知道它可以进行通配符搜索。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2012-03-05
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多