1

I have a string as:

string str = "= Fields!Change_Date.Value & Fields!Change_User.Value";

I want the output as:

Change_Date && Change_User

I am able to achieve it with multiple Regex.Replace methods as:

string str = "= Fields!Change_Date.Value & Fields!Change_User.Value";
        
string x = Regex.Replace(str, @"=? Fields!", " ");            
string y = Regex.Replace(x, @".Value", "");
string z = Regex.Replace(y, @"&", "&&");

How Can I achieve this in one go? Is that possible?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110

2 Answers2

1

You could capture word characters for Change_Date and Change_User and match in between what you don't want to keep.

Then in the replacement use the 2 capture groups only with && in between.

^= Fields!(\w+)\.Value & Fields!(\w+)\.Value$

Explanation

  • ^ Start of string
  • = Fields! Match literally
  • (\w+) Capture group 1, match 1+ word characters
  • \.Value & Fields! Match .Value & Fields!
  • (\w+) Capture group 2, match 1+ word characters
  • \.Value Match .Value
  • $ End of string

See a regex101 demo and a C# demo.

string str = "= Fields!Change_Date.Value & Fields!Change_User.Value";
string result = Regex.Replace(str, @"^= Fields!(\w+)\.Value & Fields!(\w+)\.Value$", "$1 && $2");
Console.WriteLine(result);

Output

Change_Date && Change_User
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

You could try to search and replace with group capture

var pattern = new Regex(@"[^!]+!([^.]+)[^!]+!([^.]+).*");
var input = "= Fields!Change_Date.Value & Fields!Change_User.Value";
var output = pattern.Replace(input, "$1 && $2");

See demo here

Trung Duong
  • 3,475
  • 2
  • 8
  • 9
  • Thanks a lot for this answer. However, can you please explain how does "$1 && $2" plays a role here to give the answer? – Abhishek_Singh_Rana Feb 06 '23 at 18:23
  • $1 us what was matched by the first (), ie [^.]+ and $2 the second (), [^.]+. These () and matching $N are called matching groups.. The result is (first match) && (second match) – John Williams Feb 06 '23 at 18:35