2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

スクレイピングでの改行コードの処理

Posted at

フィールドに\rが仕込まれている....!?

改行コードが混在するテキストファイルから,\r\nだけ残し,\n\rは削除したい(別の文字に置き換えたい)時があります(下参照).

あるテキストファイル
// 元の文
Hello.\r\nToday\nis\rMay.

// こんな感じにしたい
Hello.
Today is May.

解決策

以下のC#のコードで実現しました.

RemoveCRandLF.cs
var text = @"test.txt";

var result = System.Text.RegularExpressions.Regex.Replace(
	input: File.ReadAllText( text ),
	pattern: @"(?<!\r)\n|\r(?!\n)",
	replacement: " "
);

Console.WriteLine( result );

ここで,正規表現(?<!\r)\nは,前に\rが無い\nで,\r\nにはマッチしません.
同様に\r(?!\n)は,後ろに\nが無い\rで,これも\r\nにマッチしません.

細かくテストしてないので,間違ってたらごめんね.

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?