使用C#中的Regex编号列表元素

时间:2011-09-14 21:53:08

标签: c# regex

我有一个像这样的字符串:

BLOCK
    LIST1 Lorem ipsum dolor sit amet.
    LIST1 Lorem ipsum dolor sit amet.
    LIST1 Lorem ipsum dolor sit amet.
        LIST2 Lorem ipsum dolor sit amet.
        LIST2 Lorem ipsum dolor sit amet.
    LIST1 Lorem ipsum dolor sit amet.
BLOCK
    LIST1 Lorem ipsum dolor sit amet.
        LIST2 Lorem ipsum dolor sit amet.
            LIST3 Lorem ipsum dolor sit amet.
        LIST2 Lorem ipsum dolor sit amet.
    LIST1 Lorem ipsum dolor sit amet.
    LIST1 Lorem ipsum dolor sit amet.
    LIST1 Lorem ipsum dolor sit amet.

...

我想让它变成那样:

1. Lorem ipsum dolor sit amet.
    1. Lorem ipsum dolor sit amet.
    2. Lorem ipsum dolor sit amet.
    3. Lorem ipsum dolor sit amet.
        1. Lorem ipsum dolor sit amet.
        2. Lorem ipsum dolor sit amet.
    4. Lorem ipsum dolor sit amet.
2. Lorem ipsum dolor sit amet.
    1. Lorem ipsum dolor sit amet.
        1. Lorem ipsum dolor sit amet.
            1. Lorem ipsum dolor sit amet.
        2. Lorem ipsum dolor sit amet.
    2. Lorem ipsum dolor sit amet.
    3. Lorem ipsum dolor sit amet.
    4. Lorem ipsum dolor sit amet.

1 个答案:

答案 0 :(得分:2)

var input = "BLOCK\r\n    LIST1 Lorem ipsum dolor sit amet ...";

var levels = new List<string> { "BLOCK", "LIST1", "LIST2", "LIST3" };
var counter = levels.ToDictionary(level => level, level => 0);

// Replace each key word with incremented counter,
// while resetting deeper levels to 0.
var result = Regex.Replace(input, string.Join("|", levels), m =>
{
    for (int i = levels.IndexOf(m.Value) + 1; i < levels.Count; i++)
    {
        counter[levels[i]] = 0;
    }
    return (++counter[m.Value]).ToString() + ".";
});

结果:

1.
    1. Lorem ipsum dolor sit amet.
    2. Lorem ipsum dolor sit amet.
    3. Lorem ipsum dolor sit amet.
        1. Lorem ipsum dolor sit amet.
        2. Lorem ipsum dolor sit amet.
    4. Lorem ipsum dolor sit amet.
2.
    1. Lorem ipsum dolor sit amet.
        1. Lorem ipsum dolor sit amet.
            1. Lorem ipsum dolor sit amet.
        2. Lorem ipsum dolor sit amet.
    2. Lorem ipsum dolor sit amet.
    3. Lorem ipsum dolor sit amet.
    4. Lorem ipsum dolor sit amet.