Python Forum
Regular expression help - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Regular expression help (/thread-42089.html)



Regular expression help - anilrajr - May-08-2024

Hello All,

Need your help to understand what below python regular expression code does. It's from a Ansible playbook.

- { regex: '((?:hares|hagrp)\s+(?:-add|-modify|-link).*)repl(.*$)', replace: '\1vg\2' }


thanks in advance,
Anil


RE: Regular expression help - Larz60+ - May-08-2024

there is a regex expression analyzer here
(first on on search, there are many others)


RE: Regular expression help - anilrajr - May-08-2024

(May-08-2024, 08:53 AM)Larz60+ Wrote: there is a regex expression analyzer here
(first on on search, there are many others)

for some reason, I'm not able to get the correct results using this. If someone can help on this, much appreciated. Thanks.


RE: Regular expression help - snippsat - May-08-2024

If write in plain Python,look at regex101 right side has explanation.
So Ansible add some extra keyword like regex: and replace: that native to there package.
Try play around with code so eg most first match hares or hagrp...ect,if not will not replace repl.
import re

pattern = r"((?:hares|hagrp)\s+(?:-add|-modify|-link).*)repl(.*$)"
replacement = r"\1vg\2"
example_text = "hagrp -add some configuration repl with these settings"
modified_text = re.sub(pattern, replacement, example_text)
print( example_text)
print( modified_text)
Output:
hagrp -add some configuration repl with these settings hagrp -add some configuration vg with these settings



RE: Regular expression help - deanhystad - May-08-2024

You are replacing (prefix)repl(suffix) with (prefix)vg(suffix) if both prefix and suffix match a pattern.

The prefix pattern is ((?:hares|hagrp)\s+(?:-add|-match|-link).*)
hares|hagrp matches hares or hagrp. | is an OR
\s+ looks for one or more (+) whitespace characters (\s)
(?:) is needed to tell the OR that it will match hares or hagrp followed by \s+, not hares or hagrp\s+. The ?: makes this non-capturing.
The pattern is surrounded by parenthesis, so it is captured as a group.

The suffix pattern is (.*$)
.* captures any number of any character.
$ matches the end of the line.
The pattern is surrounded by parenthesis, so it is captured as a group.

replace: '\1vg\2' replaces the string with a new string if the pattern match was successful.

\1 refers to the first captured group, \2 the second. If the match was successful, the replacement string is:
(prefix group)vg(suffix group)

Using snippsat's example: "hagrp -add some configuration repl with these settings"
The prefix group is "hagrp -add some configuration "
The suffix group is " with these settings"
The new string is "hagrp -add some configuration " + "vg" + " with these settings"