在列表<字符串中插入文本>休耕模式

本文关键字:模式 插入文本 列表 字符串 | 更新日期: 2023-09-27 18:34:03

我有一些提取的文本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;
        }
    }
}


但。。有没有有效的方法可以做到这一点?

在列表<字符串中插入文本>休耕模式

最适合您的解决方案是使用 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");