Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace only matching groups and ignore non-matching groups?

Tags:

c#

regex

Regex.Replace says :

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.

In my case:

string w_name = "0x010102_default_prg_L2_E2_LDep1_LLC";
string regex_exp = @"(?:E\d)([\w\d_]+)(?:_LLC)";
w_name = Regex.Replace(w_name, regex_exp, string.Empty);

Output:

0x010102_default_prg_L2_

but I was expecting

0x010102_default_prg_L2_E2_LLC

Why is it replacing my non-matching groups(group 1 and 3)? And how do I fix this in order to get the expected output?

Demo

like image 639
greenfeet Avatar asked Aug 18 '15 13:08

greenfeet


1 Answers

Turn the first and last non-capturing groups to capturing groups so that you could refer thoses chars in the replacement part and remove the unnecessary second capturing group.

string w_name = "0x010102_default_prg_L2_E2_LDep1_LLC";
string regex_exp = @"(E\d)[\w\d_]+(_LLC)";
w_name = Regex.Replace(w_name, regex_exp, "$1$2");

DEMO

or

string regex_exp = @"(?<=E\d)[\w\d_]+(?=_LLC)";
w_name = Regex.Replace(w_name, regex_exp, string.Empty);
like image 125
Avinash Raj Avatar answered Oct 05 '22 23:10

Avinash Raj