我有一些提取的文本List<String>
,我想验证列表是否满足此标准(可能包含此模式多次,并且每个模式都是列表中的项目):
0 // A zero should always be here when two numbers are together
rn // New line
number // any positive number
rn // New line
number // Positive number, .length < = 4
rn // New line
我想要的是验证第一个零是否始终存在,如果没有,请插入它以匹配以前的列表格式。
text --> Insert a zero after this text
rn
4
rn
1234
rn
自。。。
text
rn
0 --> the inserted zero
rn
4
rn
1234
rn
所以,我知道我可以在循环中使用.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])(rn([1-9]|\d{2,})rn([1-9]|\d{2,4})rn)","$1rn0$2");