6

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

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

3 Comments

This works: pls fix group selection from "$1$2" to "$1$3". Can you explain how it works? What if I needed to replace with say string "abc" instead of empty string?
@greenfeet why I need to change $1$2 to $1$3, since I removed the second cap group present in your regex. 2. Just add abc inbetween $1 and $2 , ie $1abc$2. For the second answer, just "abc" instead of string.Empty would be enough.
you're right, I didn't notice you removed the second group, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.