16
14

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.

sedで最短一致をする

Posted at

結論

$ less test.txt
{"hoge":"fuga","piyo":"foobar"}
$ less test.txt | sed -r "s/^.*?\"hoge\":\"([^\"]*)\".*$/\1/"
fuga
  • [^A]*(クラスの否定)をうまく活用する。

やりたかったこと

  • 下記のようなjsonでkeyに一致するvalueを抜き出したかった
test.txt
{"hoge":"fuga","piyo":"foobar"}
  • しかしsedは最長一致のためこうなる
$ less test.txt | sed -r "s/\"hoge\":\"(.+?)\"/\1/"
{fuga","piyo":"foobar}
  • 違う。そうじゃない。

なぜ最初のでうまく行くか

  • []でクラス化した文字列の否定で、文字列の最初から辿る
  • 指定した文字列ではない文字列をすべてスルー
  • 目的の文字列があったらそこでサーチをやめる=最短一致

補足

  • 大抵の言語で採用されている正規表現は「やりたかったこと」で記載されている正規表現を使えば同じことができる
16
14
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
16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?