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

【Ansible】regex_フィルターの使い方まとめ

Last updated at Posted at 2025-07-01

Ansibleで regex_ 系フィルターの使い方を、共通のサンプルテキストを使ってまとめました。


基本構文

{{ string | regex_<filter>(pattern, replacement/flags) }}

使用フィルター一覧

フィルター名 説明
regex_search 正規表現で最初に一致した文字列を抽出
regex_findall 正規表現で一致したすべての文字列を抽出
regex_replace 正規表現で一致した部分を置換

前提:共通サンプルテキスト

この文字列には、ユーザー名・メールアドレス・年齢が含まれています。

sample_text: "User: Alice, Email: alice@example.com, Age: 25; User: Bob, Email: bob@example.net, Age: 30"

使用例と解説(tasks: 配下のみ)

1. regex_search

tasks:
  - name: 最初のメールアドレスを抽出
    debug:
      msg: "{{ sample_text | regex_search('[\\w._%+-]+@[\\w.-]+') }}"

出力例:

ok: [localhost] => {
    "msg": "alice@example.com"
}

解説: 最初に一致したメールアドレスを抽出します。


2. regex_findall

tasks:
  - name: 全てのメールアドレスを抽出
    debug:
      msg: "{{ sample_text | regex_findall('[\\w._%+-]+@[\\w.-]+') }}"

出力例:

ok: [localhost] => {
    "msg": [
        "alice@example.com",
        "bob@example.net"
    ]
}

解説: 全てのメールアドレスをリストとして抽出します。


3. regex_replace

tasks:
  - name: メールアドレスを [EMAIL] に置換
    debug:
      msg: "{{ sample_text | regex_replace('[\\w._%+-]+@[\\w.-]+', '[EMAIL]') }}"

出力例:

ok: [localhost] => {
    "msg": "User: Alice, Email: [EMAIL], Age: 25; User: Bob, Email: [EMAIL], Age: 30"
}

解説: メールアドレス部分を [EMAIL] に置換します。


まとめ

regex_ フィルターは、ログ解析・データ抽出・マスキング処理などに非常に便利です。
他のフィルター(例: selectattr, map)と組み合わせることで、より柔軟な処理が可能になります。

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