解析字符串并在C#中查找特定文本

时间:2011-02-21 13:18:43

标签: c# parsing text

我有一个包含的字符串,让我们说“key”字5次。每当我在该字符串中看到单词“key”时,我想打印一些文本。如何解析该字符串,找到所有“关键”字样并相应地打印文本? 5个单词“key” - 5个印刷文本。这需要在C#中完成。

提前致谢。

3 个答案:

答案 0 :(得分:7)

如何使用Regex.Matches

string input = ...
string toPrint = ...

foreach (Match m in Regex.Matches(input, "key"))
    Console.WriteLine(toPrint);

编辑:如果用“word”表示“整个单词”,则需要使用不同的正则表达式,例如:

@"\bkey\b"

答案 1 :(得分:0)

在循环中,您可以使用提供起始位置参数的substring()方法,并且每次迭代都可以提升起始位置;当您到达字符串未找到的条件时,循环退出。编辑:至于打印文本,这取决于你想要打印它的位置。编辑2:您还需要考虑目标字符串是否可以以您不认为真正“命中”的方式出现:

          The key to success, the master key, is getting off your keyster...

答案 2 :(得分:0)

我有一个扩展方法,我用它来获取子串的索引,因为.Net只提供IndexOf(第一个子串匹配的单个结果)。

public static class Extensions
{
    public static int[] IndexesOf(this string str, string sub)
    {
        int[] result = new int[0];

        for(int i=0; i < str.Length; ++i)
        {
            if(i + sub.Length > str.Length)
                break;
            if(str.Substring(i,sub.Length).Equals(sub))
            {
                Array.Resize(ref result, result.Length + 1);
                result[result.Length - 1] = i;
            }
        }
        return result;
    }
}

您可以使用扩展方法为所有键实例打印

int[] indexes = stringWithKeys.IndexesOf("key");

foreach(int index in indexes)
{
    // print something
}

我知道我的代码示例可能是最长的,但扩展方法是可重用的,您可以将它放在“实用程序”类型库中供以后使用。