如何在两个字符串之间解析文本?

时间:2015-06-04 08:35:19

标签: c# .net

我有这个方法:

private static string ExtractFromString(string text, string startString, string endString)
        {
            string matched= "";
            int index = 0;
            int index1 = 0;

            while (true)
            {
                if (index == -1)
                {
                    break;
                }
                index = text.IndexOf(startString);
                index1 = text.IndexOf(endString, index);
                matched = text.Substring(index + startString.Length,
                                         index1 - index - startString.Length);
                index = text.IndexOf(startString, index1 + 1);
            }

            return matched;
        }

并像这样使用它:

result = ExtractFromString(this.richTextBox1.Text, textBox2.Text, textBox3.Text);

结果是全局字符串var。

问题是,有时它第一次工作正常,但是当我再次尝试另一个文本时,它会被困在while循环中并且程序冻结。

1 个答案:

答案 0 :(得分:0)

代码(变体1,在startString的第一次出现与endString的最后一次出现之间进行了替换):

private static string ExtractFromString(string text, string startString, string endString)
{
    // argument control
    if (text == null) throw new ArgumentNullException("text");
    if (string.IsNullOrEmpty(startString)) throw new ArgumentNullException("startString");
    if (string.IsNullOrEmpty(endString)) throw new ArgumentNullException("endString");

    // get index of last occurence of startString and last occurence of endString
    int indexStart = text.IndexOf(startString);
    int indexEnd = text.LastIndexOf(endString);

    // check indexes
    if (indexStart < 0 || indexEnd < 0) return string.Empty;
    indexStart += startString.Length;
    if (indexStart >= indexEnd) return string.Empty;

    // return result
    return text.Substring(indexStart, indexEnd - indexStart);
}

代码(变体1,在startString的第一次出现和endString的后续出现之间进行了替换):

private static string ExtractFromString(string text, string startString, string endString)
{
    // argument control
    if (text == null) throw new ArgumentNullException("text");
    if (string.IsNullOrEmpty(startString)) throw new ArgumentNullException("startString");
    if (string.IsNullOrEmpty(endString)) throw new ArgumentNullException("endString");

    // get index of first occurence of startString
    int indexStart = text.IndexOf(startString);
    if (indexStart < 0) return string.Empty;

    // get index of first occurence of endString after startString
    indexStart += startString.Length;
    int indexEnd = text.IndexOf(endString, indexStart);
    if (indexEnd < 0) return string.Empty;

    // return result
    return text.Substring(indexStart, indexEnd - indexStart);
}

用法:

string result = ExtractFromString("x   aaa  some Text  bbb x", "aaa", "bbb");