You can capture each value and use the MatchEvaluator to process the groups.
string inputString = "[sex:he|she] took the dog with [sex:him|her]";
string result = Regex.Replace(inputString, @"\[(?<name>[^:]+):(?<value1>[^\|]+)\|(?<value2>[^\]]+)\]", Evaluator);
And the evaluator could replace any group with the appropriate response:
private string Evaluator(Match match)
{
if (match.Groups["name"].Value == "sex")
{
if (m_IsMale)
{
return match.Groups["value1"].Value;
}
else
{
return match.Groups["value2"].Value;
}
}
// No replacement, return the original value.
return match.Value;
}
The above results in either
he took the dog with him
or
she took the dog with her
0
solved C# Regular expression: how to get one of two texts with condition?