【Snowflake】Snowflake ~ 文字列操作関連 ~

■ はじめに

Snowflake の 文字列操作関連 の関数を少しづつ書いていく。

目次

【1】RPAD / LPAD
【2】SUBSTR / SUBSTRING
【3】LEN / LENGTH
【4】REPLACE
【5】CHARINDEX
【6】SPLIT_PART

【1】RPAD / LPAD

* RPAD = Right PADding? / Left PADding
* 右側・左側の文字列を埋める処理

https://docs.snowflake.com/ja/sql-reference/functions/rpad.html
https://docs.snowflake.com/ja/sql-reference/functions/lpad.html

構文

RPAD(<base>, <length_expr> [, <pad>])

<base>:操作対象文字列
<length_expr>:文字数/バイト数
<pad>:pad を左にパディング

-- 例1
select rpad('12345', 3, '*') from dual;
-- 出力結果:「123」 <= 3文字目以降は表示されない

-- 例2
select rpad('12345', 10, '*') from dual;
-- 出力結果:「12345*****」 <= 5文字目以降~10文字目まで「*」で埋める

【2】SUBSTR / SUBSTRING:

* 文字列の切り出し

https://docs.snowflake.com/ja/sql-reference/functions/substr.html

構文

SUBSTRING( <base_expr>, <start_expr> [ , <length_expr> ] )

<base_expr> : 対象文字列
<start_expr> : (開始位置は0ベースではなく、1ベース)
<length_expr> : <start_expr>から何文字目まで出すかを指定

-- 1 2 3
select substr('testing 1 2 3', 9, 5) from dual;

-- 01-2345-
select SUBSTRING('01-2345-6789', 1, 8) from dual;

【3】LEN / LENGTH

* 文字列数

https://docs.snowflake.com/ja/sql-reference/functions/length.html

-- 5
select len('hello') from dual;

-- 12
select length('01-2345-6789') from dual;

【4】REPLACE

* 文字列の置き換え

https://docs.snowflake.com/ja/sql-reference/functions/replace.html

【5】CHARINDEX

* 文字列中にある特定の文字のIndex(何番目)を返してくれる

https://docs.snowflake.com/ja/sql-reference/functions/charindex.html

-- 10
select charindex('@', 'test-test@gmail.com')

【6】SPLIT_PART

* 指定された文字列を分割し、リクエストされた部分を返す。
* パラメーターが NULL の場合、 NULL が返す

https://docs.snowflake.com/ja/sql-reference/functions/split_part.html

* 実際の使用例は、以下の関連記事を参照のこと

https://dk521123.hatenablog.com/entry/2022/10/28/000925

構文

SPLIT_PART(<string>, <delimiter>, <partNumber>)
-- <string> : 対象テキスト
-- <delimiter> : 分割する区切り文字('--'のような文字列もOK)
-- <partNumber> : 取得したいインデックス

select
  -- 127
  split_part('127.0.0.1', '.', 1),
  -- 1
  split_part('127.0.0.1', '.', -1)
;

関連記事

Snowflake ~ 基礎知識編 ~
https://dk521123.hatenablog.com/entry/2021/11/02/130111
Snowflake ~ 入門編 / Hello world
https://dk521123.hatenablog.com/entry/2021/11/22/212520
Snowflake ~ Dynamic masking ~
https://dk521123.hatenablog.com/entry/2022/10/07/102337
Snowflake ~ Partition構成のデータを取り込む ~
https://dk521123.hatenablog.com/entry/2022/10/28/000925
SQL ~ 文字列操作関連 ~
https://dk521123.hatenablog.com/entry/2013/01/21/233512
Amazon Redshift ~ 文字列結合 ~
https://dk521123.hatenablog.com/entry/2021/09/09/093855
PostgreSQL】文字列関数 ~ string_agg ~
https://dk521123.hatenablog.com/entry/2021/08/21/000000