3
5

More than 1 year has passed since last update.

Power Query で正規表現を使って取得したい Match/Matches

Posted at

背景

URL パラメーターの分解取得しようとしたら・・
前回の記事では Replace しか使わなかったので、その Match 版を記録しておく

これ使って Forms の URL から FormsId 取得して、FormsAPI を利用したカスタムコネクターが作ろう!

Replace 版は以下

Matches/Match の実装例

Matches/Matchの実装例
(expression as text, optional original as text, optional indexBeginWith1 as number ) as text =>
let
   originalText = Text.Combine({original, ""}),
   expressionText = Text.Replace(expression, "\", "\\"),
   replaceResult =  Web.Page("<script>var originalText="&"'"&originalText&"'"&";var expression=new RegExp('"&expressionText&"','g');var result=originalText.match(expression);document.write(result);</script>")
      [Data]{0}[Children]{0}[Children],

   result = if (indexBeginWith1 = null) then 
      {
         replaceResult{1}[Text]{0} as text 
      } else {
         let
            matches = Text.Split(replaceResult{1}[Text]{0}, ","),
            safeIndex = if (indexBeginWith1 <= 0 or indexBeginWith1 > List.Count(matches)) then 0 else indexBeginWith1 - 1 
         in 
            matches{safeIndex} as text
      }
in 
  result{0}

見た目

image.png

パラメータ説明

  • expression
    • 正規表現のパターン
  • original
    • 正規表現適用対象のテキスト
  • indexBeginWith1
    • 取得対象の位置指定
      • 省略(null): 一致したもの全部
      • 1 ~ 取得結果内の長さ: 見つかったものの中の指定位置取得
      • 0 以下 or 長さ超えた値: index 1 として取得

変換テスト例

image.png

上記のコード
let
    ソース = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WyigpKSi20tcvzMwsSdRLzs/VTylKTCsp1rc0MzG0MDY2tzC1SEs2MTQ2STMwU9JRiolJ0VaK1SFHY3m1iY5ZLZmaU6oNTYF6YwE=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Original = _t, Expression = _t]),
    変更された型 = Table.TransformColumnTypes(ソース,{{"Original", type text}, {"Expression", type text}}),
    呼び出されたカスタム関数2 = Table.AddColumn(変更された型, "Index 0", each Matches([Expression], [Original], 0)),
    呼び出されたカスタム関数 = Table.AddColumn(呼び出されたカスタム関数2, "Index 1", each Matches([Expression], [Original], 1)),
    呼び出されたカスタム関数1 = Table.AddColumn(呼び出されたカスタム関数, "Index 2", each Matches([Expression], [Original], 2)),
    呼び出されたカスタム関数3 = Table.AddColumn(呼び出されたカスタム関数1, "index 3", each Matches([Expression], [Original], 3)),
    呼び出されたカスタム関数4 = Table.AddColumn(呼び出されたカスタム関数3, "Index 4", each Matches([Expression], [Original], 4)),
    呼び出されたカスタム関数5 = Table.AddColumn(呼び出されたカスタム関数4, "index null", each Matches([Expression], [Original], null))
in
    呼び出されたカスタム関数5

あとがき

さぁ準備は出来た!
あとは、カスタムコネクターへ

keyword

how to use match regular expression in powerquery

3
5
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
3
5