CinCout
CinCout

Reputation: 9619

Is this possible via regex conditional?

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

Answers (2)

mkHun
mkHun

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

Aran-Fey
Aran-Fey

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:

  1. Change the pattern so that it only matches if it finds notation1, i.e. regex=(text1)(notation1), replacement=newtext1\2.
  2. If your programming language supports it, create a substitution function that checks the contents of group 2 and returns the desired replacement string. For example in python you could do: re.sub(r'(text1)(notation1)', lambda match: 'newtext1notation1' if match.group(2)=='notation1' else 'text1notation1', 'text1notation1')

Upvotes: 1

Related Questions