Filter the substring corresponding to the pattern from the user variable, and assign the substring to the substring of another variable

Say we have a long mystr carrier string. We have a regular expression template substr_pattern , and the substring corresponding to this template should be filtered out from mystr and assigned to another variable substr . There seems to be no obvious way to do this in inaccessible documents on playbook_filters , although it is easy to do this with the py module re in itself.

There are three methods given in the documents that cannot be processed, and none of them will solve my problem:

  • match : this filter returns true / false depending on whether the entire pattern matches the entire string, but does not return a matched group / substring.

  • search : Used to filter substr in a larger string. But, like match , only true / false is returned and does not match the group / substring that is needed here.

  • regex_replace : used to replace the matched template in a string with another string. But it is unclear how to register the substring / group corresponding to the mapped pattern into a new variable.

Is there something I am missing? Or is it a missing feature out of reach?

Strong version: 2.1

Example:

 mystr: "This is the long string. With a url. http://example.org/12345" pattern: "http:\/\/example.org\/(\d+)" substr: 12345 # First matched group ie \\1 

Summary: how to get the substring corresponding to pattern from mystr and register this variable with substr variable?

+5
source share
1 answer

If you can change the template, you can use the regex_replace filter and replace the whole line with only matched digits.

 mystr | regex_replace('^.*http:\/\/example.org\/(\d+).*?$', '\\1') 

To assign the result to a new variable, you can use the set_fact module.

 - set_fact: substr: "{{ mystr | regex_replace('^.*http:\/\/example.org\/(\d+).*?$', '\\1') }}" 
+9
source

All Articles