1
0

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 1 year has passed since last update.

正規表現の活用 CSVの体裁を変えずに特定のデータを抽出する

Posted at

csvの体裁を変えずに特定のデータだけ抽出したい

エンジニアを約1年やってきて、こんな時正規表現が役立った!という場面を記録。

使用アプリケーション

  • サクラエディタ
  • Visual Studio Code

たとえば、下記のようなデータがあり、リンゴが含む行だけ抽出してCSVの形を維持したい場面があるとします。

fruits.csv
    "ID", "果物の名前", "色",
    "01", "リンゴ", "赤",
    "02", "みかん", "オレンジ",
    "03", "リンゴ", "青",
    "04", "ブドウ", "紫"

抽出と聞いてすぐに思いつく方法は、Excelでフィルターをかける方法だと思います。しかし、その方法であるとCSVをExcelのシートに取り込む際にダブルクォーテーションが削除されてしまいます。そのため、ここで活用できるのが正規表現です。

私が使用した正規表現は下記です。

^(?!.*リンゴ).*$

特定の文字を含まない列が対象となる正規表現です。こちらで対象となる行を空文字で置換し、さらに改行を示す下記の正規表現を空文字で置換することで「リンゴ」を含む行のみ抽出することができます。

^\r\n

まとめ

この正規表現はただ○○を含む行のみを抽出したいという時によく使用しています。
一度履歴として残っていると、いざとなったときに使用することができるため特にサクラエディタで使用することをおすすめします。

English ver.

How to extract specific data from a CSV without altering its format

After working as an engineer for about a year, I've encountered situations where regular expressions proved to be useful! Here's a record of one such instance:

Applications Used

  • Sakura Editor
  • Visual Studio Code

For example, let's say you have the following data, and you want to extract only the rows containing "リンゴ" (apple) while maintaining the CSV format:

fruits.csv
    "ID", "果物の名前", "色",
    "01", "リンゴ", "赤",
    "02", "みかん", "オレンジ",
    "03", "リンゴ", "青",
    "04", "ブドウ", "紫"

The first thought for extraction might be using Excel's filtering. However, using that method, when importing CSV into an Excel sheet, the double quotations get removed. Therefore, regular expressions can be handy in this situation.

The regular expression I used is as follows:

^(?!.*リンゴ).*$

This regular expression targets lines that do not contain a specific word. By using this regular expression to replace matching lines with an empty string and further using the following regular expression to replace newlines with empty strings, you can extract only the lines containing "リンゴ" (apple):

^\r\n

Summary

I frequently use this regular expression when I need to extract only lines containing specific keywords. Once it's saved in your history, you can easily use it when needed, making it especially useful in Sakura Editor.

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?