String Sync recursively

I am trying to extract information from a string - to format fortran string. The string is formatted as follows:

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

with formatting fields separated by "," and formatting groups inside the brackets, with a number in front of the brackets indicating how many times the formatting pattern is repeated. Thus, the line above expands to:

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'

I am trying to do something in C # that will expand the string matching this pattern. I started to work around this with a lot of switches and if there were statements, but I wonder if I am not mistaken in this?

I was wondering if any Regex wizzard thinks that regular expressions can do it in one fell swoop? I don’t know anything about regular expressions, but if this can solve my problem, I’m thinking about learning how to use them after a while ... on the other hand, if regular expressions can't figure it out, then I would rather spend looking to another method.

+5
source share
4 answers

I would suggest using a recusive method similar to the example below (not tested):

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");
}

You may need to change some parts of the code, but I used this method when writing a simple compiler. Although this is not complete, just an example.

0
source

Regex:) .

// regex to match the inner most patterns of n(X) and capture the values of n and X.
private static readonly Regex matcher = new Regex(@"(\d+)\(([^(]*?)\)", RegexOptions.None);

// create new string by repeating X n times, separated with ','
private static string Join(Match m)
{
    var n = Convert.ToInt32(m.Groups[1].Value); // get value of n
    var x = m.Groups[2].Value; // get value of X
    return String.Join(",", Enumerable.Repeat(x, n));
}

// expand the string by recursively replacing the innermost values of n(X).
private static string Expand(string text)
{
    var s = matcher.Replace(text, Join);
    return (matcher.IsMatch(s)) ? Expand(s) : s;
}

// parse a string for occurenses of n(X) pattern and expand then.
// return the string as a tokenized array.
public static string[] Parse(string text)
{
    // Check that the number of parantheses is even.
    if (text.Sum(c => (c == '(' || c == ')') ? 1 : 0) % 2 == 1)
        throw new ArgumentException("The string contains an odd number of parantheses.");

    return Expand(text).Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
+1

. , , , . , .

( : )

0

. , :

private static string ExpandBrackets(string Format)
    {
        int maxLevel = CountNesting(Format);

        for (int currentLevel = maxLevel; currentLevel > 0; currentLevel--)
        {
            int level = 0;
            int start = 0;
            int end = 0;

            for (int i = 0; i < Format.Length; i++)
            {
                char thisChar = Format[i];
                switch (Format[i])
                {
                    case '(':
                        level++;
                        if (level == currentLevel)
                        {
                            string group = string.Empty;
                            int repeat = 0;

                            /// Isolate the number of repeats if any
                            /// If there are 0 repeats the set to 1 so group will be replaced by itself with the brackets removed
                            for (int j = i - 1; j >= 0; j--)
                            {
                                char c = Format[j];
                                if (c == ',')
                                {
                                    start = j + 1;
                                    break;
                                }
                                if (char.IsDigit(c))
                                    repeat = int.Parse(c + (repeat != 0 ? repeat.ToString() : string.Empty));
                                else
                                    throw new Exception("Non-numeric character " + c + " found in front of the brackets");
                            }
                            if (repeat == 0)
                                repeat = 1;

                            /// Isolate the format group
                            /// Parse until the first closing bracket. Level is decremented as this effectively takes us down one level
                            for (int j = i + 1; j < Format.Length; j++)
                            {
                                char c = Format[j];
                                if (c == ')')
                                {
                                    level--;
                                    end = j;
                                    break;
                                }
                                group += c;
                            }

                            /// Substitute the expanded group for the original group in the format string
                            /// If the group is empty then just remove it from the string
                            if (string.IsNullOrEmpty(group))
                            {
                                Format = Format.Remove(start - 1, end - start + 2);
                                i = start;
                            }
                            else
                            {
                                string repeatedGroup = RepeatString(group, repeat);
                                Format = Format.Remove(start, end - start + 1).Insert(start, repeatedGroup);
                                i = start + repeatedGroup.Length - 1;
                            }
                        }
                        break;

                    case ')':
                        level--;
                        break;
                }
            }
        }

        return Format;
    }

CountNesting() , . RepeatString() .

0

All Articles