Reputation: 23749
Input: This AbT5xY\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\nmangoUvW test
Following RegEx gives the output: This SomeFruitUvW is a test SomeFruitUvW is a test and AbT5xrAppleUvW and another SomeFruitUvW test.
Regex.Replace(st, "AbT5xY\\s*(Apple)|(mango)", "SomeFruit");
But what I need is that if AbT5xY
is followed by Apple
then replace AbT5xYApple
with Fruit1
; and if AbT5xY
is followed by mango
replace AbT5xYmango
with Fruit2
. Hence,
Desired output: This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test.
Note:
AbT5xY
and Apple or AbT5xY
and mango. Also AbT5xrAppleUvW
is correctly not matched since it has AbT5xr
and not AbT5xY
before Apple.Upvotes: 1
Views: 263
Reputation: 626748
You may capture the Apple
and mango
into Group 1 and when replacing, use a match evaluator, where you can check the Group 1 value, and then perform the necessary replacement based on the check result:
var pat = @"AbT5xY\s*(Apple|mango)";
var s = "This AbT5xY\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\nmangoUvW test";
var res = Regex.Replace(s, pat, m =>
m.Groups[1].Value == "Apple" ? "Fruit1" : "Fruit2");
Console.WriteLine(res);
// => This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test
See the C# demo.
The AbT5xY\s*(Apple|mango)
regex matches AbT5xY
, then 0+ whitespaces (note a single backslash as I used a verbatim string literal) and then matches and captures either Apple
or mango
into Group 1. The m.Groups[1].Value == "Apple"
if Group 1 value is Apple
, and then proceeds to replace the match.
Upvotes: 4