I wonder how to substitute group 1 with certain string by regex in python.
Question1:
str = "aaa bbb ccc"
regex = "\baaa (bbb)\b"
repl = "111 bbb 222"
Use regex to match str, matched "aaa bbb", and replace group1 "bbb" with "111 bbb 222", and get the result "aaa 111 bbb 222 ccc"
str_repl = "aaa 111 bbb 222 ccc"
Thanks for @RomanPerekhrest and @janos 's lookbehind method.
And I wonder how to solve a more general scenario:
Question2:
s1 = "bBb"
regex = "(?<=\baaa )" + s1 + "\b" # may not suitable
repl = "XxX " + s1 + " YyY"
target:
s0 = "aaa bBb ccc"
s0_repl = "aaa XxX bBb YyY ccc"
s1 = "aaa bbb ccc"
no match
s2 = "AAA bBb ccc"
s2_repl = "AAA XxX bBb YyY ccc"
Ignore the case for substring except of s1 when matching in original string.
Question3:
s1 = "bbb"
regex = "(?<=\baaa )" + s1 + "\b" # may not suitable
repl = "XxX " + s1 + " YyY"
target:
s0 = "aaa bBb ccc"
s0_repl = "aaa XxX bBb YyY ccc"
s1 = "aaa bbb ccc"
s1_repl = "aaa XxX bbb YyY ccc"
s2 = "AAA BBB ccc"
s2_repl = "AAA XxX BBB YyY ccc"
Ignore the case for substring except of s1 when matching & substituting in original string.
Question4:
If there is a way to substitute group 1 on original string by regex on python?