在模式</string>之后的List <string>中插入文本

时间:2013-10-04 20:26:23

标签: c# c#-4.0

我有List<String>一些提取的文本,我想验证列表是否符合此条件(可能包含此模式的多次,每个都是列表中的项目):

0      // A zero should always be here when two numbers are together
\r\n   // New line
number // any positive number
\r\n   // New line
number // Positive number, .length < = 4
\r\n   // New line

我想要的是验证第一个零是否始终存在,如果不存在,则插入它以匹配先前的列表格式。

text  --> Insert a zero after this text
\r\n
4
\r\n
1234
\r\n

要...

text
\r\n
0     --> the inserted zero
\r\n
4
\r\n
1234
\r\n

所以,我知道我可以在循环中使用.Insert(index, string),事实上我使用for来循环列表并进行大量丑陋的验证

public Regex isNumber = new Regex(@"^\d+$");

// When the list is been build and a possible match is found call this method:
private void CheckIfZeroMustBeAdded(List<string> stringList)
{
    int counter = 0;

    for (int i = stringList.Count - 1; i > 1; i--)
    {
        if (stringList[i].Equals(Environment.NewLine))
        {
            // Do nothing
        }
        else if (counter == 2) 
        {
            if (!stringList[i].Equals("0"))
            {
                stringList.Insert(i, string.Format("{0}{1}", Environment.NewLine,"0"));
                break;
            }
        }
        else if (ExtractionConst.isNumber.Match(stringList[i]).Success && !stringList[i].Equals("0")
        {
            // There are two numbers together
            counter++;
        }
        else
        {
            break;
        }
    }
}


但是..有没有有效的方法呢?

1 个答案:

答案 0 :(得分:1)

最适合您的解决方案是使用Regex,试试这个:

//Add using System.Text.RegularExpressions first
string input = ....;// It's up to you
string output = Regex.Replace(input,"([^0])(\r\n([1-9]|\\d{2,})\r\n([1-9]|\\d{2,4})\r\n)","$1\r\n0$2");