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

`regexp_replace`関数を使って文字列置換する際は、繰り返しを全部置換する`g`オプションをつける

Posted at

改行コードを複数含む文字列に対して、登場するすべての改行コードを<改行>という文字列に置換するSQLのサンプル。もちろん、改行コードに限らずregexp_replace関数で他の文字列を置換する際にも応用が効きます。

regexp_replace関数にgオプションをつけないと、改行コードが文字列中に複数回登場した際、1つ目のものしか置換できません。

select
	regexp_replace(
		E'これは\nLF\n\rCR\r\r\nCR+LF\r\nが混在する文字列です'
		, E'(\r\n|\r|\n)'
		, '<改行>'
		, 'g' -- このオプションが必要
		) AS "全部置換できるパターン"
	,regexp_replace(
		E'これは\nLF\n\rCR\r\r\nCR+LF\r\nが混在する文字列です'
		, E'(\r\n|\r|\n)'
		, '<改行>'
		) AS "1つ目の改行しか置換できないパターン"
;

実行結果:

全部置換できるパターン 1つ目の改行しか置換できないパターン
これは<改行>LF<改行>と<改行>CR<改行>と<改行>CR+LF<改行>が混在する文字列です これは<改行>LF

CR

CR+LF
が混在する文字列です
0
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
0
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?