CSV のようなファイルのすべての新しい行を一致させようとしています。問題は、巨大なファイルには常にいくつかの壊れた行が含まれていることです。次に例を示します。
123|some string field|person 123|some optional open comment|324|213
133|some string field|person||324|213
153|some string field|person 123|some comment|324|213
126|some string field|another id|some open and
new line comment|324|213
153|string field|person 123|some comment|324|213
153|string field|person 123|another broken line
comment|324|213
133|field|person||324|213
したがって、このケースを解決するために、次のロジックを使用しました。
string ZSUR = File.ReadAllText(filePath);
string originalFilePath = filePath;
// Regular Expression to fix line break issues
Regex RE = new Regex(@"[\r\t\n]+([^0-9\r\t\n]{3}[^|\r\t\n])");
ZSUR = RE.Replace(ZSUR, "$1");
// Backup the original file
string[] backupFilePath = Regex.Split(filePath, @".txt$");
File.Delete(backupFilePath[0] + "_BACKUP.txt");
File.Move(originalFilePath, backupFilePath[0] + "_BACKUP.txt");
// And then save on the same path the fixed file
File.WriteAllText(originalFilePath, ZSUR);
正しい行の最初の部分は常に 3 桁の数字で始まり、その後にパイプが続くため、ケースの 90% が解決されます。
しかし、次のようなケースと一致しない理由はわかりません。
126|some string field|another id|some open and
double newlined
123 coment|324|213
153|some string field|person 123|some comment|324|213
153|some string field|person 123|some comment|324|213
153|string field|person 123|Please split this line
31 pcs: 05/03/2013
31|324|213
153|some string field|person 123|some comment|324|213
ご覧のとおり、これを解決するには別のアプローチが必要です。パイプを N 回使用した後、その迷惑なコメント フィールドがそこにあることを知っています。それで、行の先頭から N パイプの後にすべての新しい行と類似のものを一致させる方法はありますか?
他のアイデアも大歓迎です。
編集:答えてくれてありがとう。
次の正規表現を使用してこれを解決しました。
(?<!\|[CA]?\|([0-9]{2}.[0-9]{2}.[0-9]{4})?)[\n\r]+
もちろん、私の実際のファイルは投稿された例とは少し異なりますが、主なアイデアは、前に
(?<! ... )
表現。