Reputation: 9619
Suppose I have successfully captured the following groups:
/1 "text1"
/2 "notation1"
Now, I want to replace /1
with "newtext1"
iff /2
contains "notation1"
. Is this possible via conditional statement?
Or by any other method?
Upvotes: 2
Views: 80
Reputation: 5927
Suppose you are in perl the substitution will done by e
(evaluate string as an operator) modifier with ternary conditional operator.
$s = "text1 notation1";
$s=~s/(\w+)\s(\w+)/($2 eq "notation1")?"newtext1 $2":"$1 $2"/e;
print $s;
Upvotes: 0
Reputation: 43166
Regex has no conditional statement that allows you to check if a capture group has captured a certain value. You have two options:
notation1
, i.e. regex=(text1)(notation1)
, replacement=newtext1\2
.re.sub(r'(text1)(notation1)', lambda match: 'newtext1notation1' if match.group(2)=='notation1' else 'text1notation1', 'text1notation1')
Upvotes: 1