6
7

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

goで設定ファイルのパーサを書いていた時に、
いわゆる行内の#から始まるコメントを除外したい時の正規表現が見つからなかったため、自作しました。

以下のパターンのコメントをサポートします。

A. 行頭コメント
# comment
key = value

B. 後置コメント
key = value   # comment

C. ダブルクォート内に#が存在する場合の後置コメント
key = "#value"  # comment

AとBのように、#以降を単純に取り除く場合は、以下の正規表現にマッチする部分を削除するだけで問題無いと思います。

# .*$

今回は、Cに適用すると、残したい部分も含めて削除してしまうので、下記の様に書いてみました。
(ついでにシングルクォートも対応しました)

^((?:[^#'"]|"[^"]*"|'[^']*')*)(#.*)?$

この正規表現を用いて、置換を行い、$1だけ残します。
goで書くとこんな感じです。

package main

import (
  "fmt"
  "regexp"
)

func main() {
  commentRegex := regexp.MustCompile(`^((?:[^#'"]|"[^"]*"|'[^']*')*)(#.*)?`)
  result := commentRegex.ReplaceAllString(`key = "#value" # comment`, "$1")
  fmt.Println(result)
  // Output: key = "#value"
}

注意点としては、見ての通り一行ずつ置換する必要があります。

6
7
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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?