我正在尝试从字符串中提取信息-具体来说是Fortran格式字符串。字符串的格式如下:

F8.3, I5, 3(5X, 2(A20,F10.3)), 'XXX'

用“,”分隔的格式字段和括号内的格式组,括号前的数字表示格式模式重复的连续次数。因此,上面的字符串扩展为:
F8.3, I5, 5X, A20,F10.3, A20,F10.3, 5X, A20,F10.3, A20,F10.3, 5X, A20,F10.3, A20,F10.3, 'XXX'

我正在尝试用c做一些东西来扩展一个符合该模式的字符串。我已经开始用很多开关和if语句来讨论这个问题,但是我想知道我是否没有用错误的方式来讨论这个问题?
我基本上想知道是否有一些regex wizzard认为正则表达式可以一蹴而就地做到这一点?我对正则表达式一无所知,但如果这能解决我的问题,我正在考虑花点时间学习如何使用它们…另一方面,如果正则表达式不能解决这个问题,那么我宁愿花时间研究另一种方法。

最佳答案

我建议使用如下示例(未测试)那样的重复方法:

ResultData Parse(String value, ref Int32 index)
{
    ResultData result = new ResultData();
    Index startIndex = index; // Used to get substrings

    while (index < value.Length)
    {
        Char current = value[index];

        if (current == '(')
        {
            index++;
            result.Add(Parse(value, ref index));
            startIndex = index;
            continue;
        }
        if (current == ')')
        {
            // Push last result
           index++;
           return result;
        }

        // Process all other chars here
    }

    // We can't find the closing bracket
    throw new Exception("String is not valid");
}

您可能需要修改代码的某些部分,但我在编写简单编译器时使用了此方法。虽然还没有完成,只是一个例子。

09-20 23:56