2013-01-01 33 views
0

我有一个服务器生成的文件 - 我无法控制如何生成或格式化此文件。我需要检查每一行以设定长度的字符串开始(在本例中为21个数字字符)。如果一行不符合该条件,我需要将它加入到上一行,并在读取并更正整个文件后,将其保存。我正在为目录中的很多文件执行此操作。检查行是否匹配正则表达式

到目前为止,我有:

 Dim rgx As New Regex("^[0-9]{21}$") 

     Dim linesList As New List(Of String)(File.ReadAllLines(finfo.FullName)) 

     If linesList(0).Contains("BlackBerry Messenger") Then 
      linesList.RemoveAt(0) 
      For i As Integer = 0 To linesList.Count 
        If Not rgx.IsMatch(i.ToString) Then 
         linesList.Concat(linesList(i-1)) 
       End If 

      Next 
     End If 
     File.WriteAllLines(finfo.FullName, linesList.ToArray())[code] 

有一个之前和代码块循环遍历源目录,工作正常的所有文件后声明。

希望这不是太糟糕阅读:/

+1

你需要检查每行_begins_与21位数字,但你锚你的正则表达式到最后 - 为什么? – fge

+0

不,那个“$”不应该在那里......漫漫长夜!谢谢。其余的仍然有点困难。 – user1171534

+0

在'rgx.IsMatch(i.ToString)'上,它不会匹配,因为'i'是循环变量和'Integer'。我假设你的意思是'rgx.IsMatch(linesList(i))'? – rmobis

回答

0

我没想到你的解决方案是什么好,你没有上串接线。这是一个不同的方法:

Dim rgx As New Regex("^[0-9]{21}") 
Dim linesList As New List(Of String)(File.ReadAllLines(finfo.FullName)) 

' We will create a new list to store the new lines data 
Dim newLinesList As New List(Of String)() 

If linesList(0).Contains("BlackBerry Messenger") Then 
    Dim i As Integer = 1 
    Dim newLine As String 
    While i < linesList.Count 
     newLine = linesList(i) 
     i += 1 

     ' Keep going until the "real" line is over 
     While i < linesList.Count AndAlso Not rgx.IsMatch(linesList(i)) 
      newLine += linesList(i) 
      i += 1 
     End While 

     newLinesList.Add(newLine) 
    End While 
End If 

File.WriteAllLines(finfo.FullName, newLinesList.ToArray()) 
+1

梦幻般的答案,我确实看到我要去哪里完全错误......谢谢! – user1171534