Home > Net >  Retrive only replacement template of regex in C#
Retrive only replacement template of regex in C#

Time:05-26


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

Ricko 124

Thaaaanks

CodePudding user response:

You should use Regex.Match to extract the text and then concatenate Group 2 and Group 1 values:

Match m = Regex.Match(text, regex, RegexOptions.Multiline);
if (m.Success) {
    String result = $"{m.Groups[2].Value} {m.Groups[1].Value}";
    Console.WriteLine(result);
}

See the C# demo.

Note:

  • RegexOptions.Multiline is added since your string contains multiple lines, and you need to match start of a line with ^
  • Regex.Match returns the first match from the string
  • if (m.Success) is used to check if there was a match with the given string and pattern
  • m.Groups[1].Value contains the first capturing group value, m.Groups[2].Value contains the second capturing group value, etc.

CodePudding user response:

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
  • Related