Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrive only replacement template of regex in C#

can i get only the substitution of the Regex.Replace?
Example.

String text = @"asdfgs sda gsa ga s
SECTOR:124 NAME:Ricko
asdfgs sda gsa ga s";
String regex = "^SECTOR:(\d+) NAME:(\w+)";
String substitution = "$2 $1";

String result = Regex.Replace(text, regex, substitution);

Console.WriteLine(result);

Normal result

asdfgs sda gsa ga s
Ricko 124

Wanted result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Ricko 124

Thaaaanks

>Solution :

You are not matching all the characters around what you want to keep that should be deleted.

You could have the dot match a newline and using the multiline flag for the anchor.

(?sm).*?^SECTOR:(\d+) NAME:(\w+).*

The pattern matches:

  • (?sm) Inline flags having the dot matching a newline and multiline
  • .*? Match any character including a newline as least as possible
  • ^ Start of string
  • SECTOR:(\d+) NAME:(\w+) Capture 1+ digits in group 1 for SECTOR: and capture 1+ word chars in group 2 for NAME:
  • .* Match the rest of the lines

Example

String text = @"asdfgs sda gsa ga s
SECTOR:124 NAME:Ricko
asdfgs sda gsa ga s";
String regex = @"(?sm).*?^SECTOR:(\d+) NAME:(\w+).*";
String substitution = "$2 $1";

String result = Regex.Replace(text, regex, substitution);

Console.WriteLine(result);

Output

Ricko 124
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading