22
13

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 3 years have passed since last update.

Microsoft Power BIAdvent Calendar 2021

Day 15

Power Query で正規表現を使って置換したい

Last updated at Posted at 2021-07-08

何のため?

Delimiterが無く、可変長の部分文字列の抽出がしたい時にやっぱり正規表現で、いつも通り使いたいなぁ・・と思ったわけです。

で、探してみたら Power Query Regular Expression Hack JavaScript使う方法があったので自分用に改造してみました。

変換の実装例

ReplaceAsRegEx
(expression as text, optional original as text,  optional replacement as text) as text =>
let
   originalText = Text.Combine({original, ""}),
   expressionText = Text.Replace(expression, "\", "\\"),
   replaceText = Text.Combine({replacement, ""}),
   replaceResult =  Web.Page("<script>var originalText="&"'"&originalText&"'"&";var replacement="&"'"&replaceText&"'"&";var expression=new RegExp('"&expressionText&"','g');var result=originalText.replace(expression,replacement);document.write(result);</script>")
      [Data]{0}[Children]{0}[Children],

   result = if (List.Count(replaceResult) <= 1) then
   { 
      "" as text // 変換して何も残らない場合
   } else if (replaceResult{1}[Text]{0} = null) then
   {
      originalText   as text// 何も見つからない場合
   }  else {
      replaceResult{1}[Text]{0} as text
   }
in 
   result{0}

見た目

image.png

変換テスト例

image.png

上記のテストコード
let
    ソース = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("lZLRDoIgFIafJdZFqWyY3XTVeo3QGGHlhZsXXbT19B1Q1LYDHhnC5v9x+Pl3pGT6bupHfiiOzxfLWFl+Uti0+6osINuJifV41goa/gYpDwUYd03XbIYVReZEfOI2trAp72MQUHDOKRgoJwU/Vda1yD0r8kjFKSYYES4alGy6t7t0+R0OJZG3nXHwPj2v4xPPq4UDPZ8Qy/c01YxZkckA0/IzvJlI6AKrKIV3QvFXE+BQb7VEo2RSav4dX997xKgLv+IZVT8=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [OriginalText = _t, Expression = _t, Replacement = _t, Correct = _t]),
    呼び出されたカスタム関数 = Table.AddColumn(ソース, "RexExReplace", each ReplaceAsRegEx([Expression], [OriginalText], [Replacement])),
    追加されたカスタム = Table.AddColumn(呼び出されたカスタム関数, "Assertion", each [Correct]=[RexExReplace])
in
    追加されたカスタム

あとがき

Power Apps での IsMatch、Match、および MatchAll 関数
これ見つけて、正規表現あるじゃん!って思ったんですが・・Appsでした・・悲しい
どっかに実装されててもおかしくないと思うんですけどね・・

description

how to use regular expression in powerquery

参考情報

Power Query M 式言語
Regular Expressions support in Power Query python とかRでってのも出来るのかな?

22
13
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
22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?