LoginSignup
1
2

More than 1 year has passed since last update.

PostgreSQLで正規表現にマッチする文字列を取得する

Posted at

PostgreSQLで正規表現にマッチした特定の文字列を抽出する方法のメモ。マニュアルを読むと色々書いてあるけど、高度なことをしなければ、substring を使っておけばOK

具体例

キャプチャ用の括弧なしだと、マッチした部分文字列が返る。

select substring('psql (PostgreSQL) 10.18', '^\w+');      --> psql
select substring('psql (PostgreSQL) 10.18', '\(\w+\)');   --> (PostgreSQL)
select substring('psql (PostgreSQL) 10.18', '[\d\.]+$');  --> 10.18

キャプチャ用の括弧をつけると、括弧の中にマッチした文字列だけが返る。こちらを使うケースの方が多そう。

select substring('psql (PostgreSQL) 10.18', '\((\w+)\)');   --> PostgreSQL
select substring('psql (PostgreSQL) 10.18', '(\d+)\.\d+');  --> 10
select substring('psql (PostgreSQL) 10.18', '\d+\.(\d+)');  --> 18

キャプチャ用の括弧を複数つけると、最初の括弧の中にマッチした文字列だけが返る。そのため、キャプチャさせたくない括弧には ?: を付けるとスキップできる。

select substring('psql (PostgreSQL) 10.18', '(\d+)\.(\d+)');    --> 10
select substring('psql (PostgreSQL) 10.18', '(?:\d+)\.(\d+)');  --> 18

そもそもマッチしない場合は null になる。

select substring('psql (PostgreSQL) 10.18', 'mysql');  --> null

おまけ

substring(<string>, <pattern>) の代わりに substring(<string> from <pattern>) としても同じ。

select substring('psql (PostgreSQL) 10.18' from '^\w+');  --> psql

確認環境

  • PostgreSQL 10.18

参考文献

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