HyperioN
HyperioN

Reputation: 3928

Extract a word from multiline string

I have a multiline string from which I have to extract a word.

Sample String:

`Locale LANG set to the following: "en"
Scheduled for (Exp) 02/12/20 (#4662) on CSC2CXN00002555.  Batchman LIVES.  Limit: 80, Fence: 0, Audit Level: 1`

I have to extract only the word CSC2CXN00002555. I tried using regex_search ansible module

{{ input_string | regex_search('on(.*).  Batchman', multiline=True) }}

But I'm getting the whole pattern as output:

{
"msg": "on CSC2CXN00002555.  Batchman"
}

Is there a way to achieve this?

Upvotes: 0

Views: 282

Answers (2)

sebthebert
sebthebert

Reputation: 12507

You should use regex_replace if you want to return only a smaller part of your regex.

You can handle the multiline by splitting on newline.

---
- hosts: localhost
  gather_facts: no

  vars:
    input_string: |
        Locale LANG set to the following: "en"
        Scheduled for (Exp) 02/12/20 (#4662) on CSC2CXN00002555.  Batchman LIVES.  Limit: 80, Fence: 0, Audit Level: 1

  tasks:

    - name: "it will return 'CSC2CXN00002555'"
      debug:
        msg: "{{ input_string.split('\n') | regex_replace('^.+ on (\\w+)\\.  Batchman .+', '\\1') }}"

And for a better understanding of regexes, play with regex101.

Explanation of the regex here: https://regex101.com/r/4RqNb4/1

Upvotes: 1

bosari
bosari

Reputation: 2000

Try using this regex - CS(.*)5.

{{ input_string | regex_search('CS(.*)5', multiline=True) }}

Upvotes: 0

Related Questions