-1
extern const BP_UINT8 g_SysMapDis_<DIST_N>[];

I want to replace the 'DIST_N' with '0' or '1', like:

extern const BP_UINT8 g_SysMapDis_0[];

So I do something like this

    Regex REGEX_CODE_BLOCK_DIST_N = new Regex(@"(.+)(<DIST_N>)(.+)");
    int n = 0;
    string codeBlock = "extern const BP_UINT8 g_SysMapDis_<DIST_N>[];";
    string ret += REGEX_CODE_BLOCK_DIST_N.Replace(codeBlock, "$1" + n + "$3");

I only get this

$10[];// should be "extern const BP_UINT8 g_SysMapDis_0[];"

So how to append a number after "$1"?

7
  • "should be "extern const BP_UINT8 g_SysMapDis_0[];" that doesnt have a $1 ? Commented Jan 1, 2019 at 7:13
  • @AnuViswan, the $1 should be replace with "extern const BP_UINT8 g_SysMapDis_" Commented Jan 1, 2019 at 7:17
  • so, is your expected output be "extern const BP_UINT8 g_SysMapDis_$10$3[];" or just "extern const BP_UINT8 g_SysMapDis_0[];"? Commented Jan 1, 2019 at 7:18
  • @AnuViswan "extern const BP_UINT8 g_SysMapDis_0[];" is what I expect Commented Jan 1, 2019 at 7:20
  • I have updated my answer. Kindly check if that resolves your issue Commented Jan 1, 2019 at 7:21

2 Answers 2

4

In this simple case you can use string replace instead of a regex:

string codeBlock = "extern const BP_UINT8 g_SysMapDis_<DIST_N>[];";
string ret = codeBlock.Replace("<DIST_N>", "0");

Specifically in your case, your regex replacements string was "$1" + n, which has the value "$10" - so it ended up looking for the 10th group. The solution is to use "${1}0" instead, separating the group from the following "0". For example:

var s = Regex.Replace("123abc",@"(.)","${1}0");

See also:

Sign up to request clarification or add additional context in comments.

Comments

3

Your regex needs to be following as that is the string you are trying to replace.

"(<DIST_N>)"

Complete Code

Regex REGEX_CODE_BLOCK_DIST_N = new Regex(@"(<DIST_N>)");
int n = 0;
string codeBlock = "extern const BP_UINT8 g_SysMapDis_<DIST_N>[];";
string ret = REGEX_CODE_BLOCK_DIST_N.Replace(codeBlock,  n.ToString() );

Output

extern const BP_UINT8 g_SysMapDis_0[];

Additional Comment

Please note you could use a more simpler string.Replace in this case, instead of using Regex.

string ret = codeBlock.Replace("<DIST_N>",  n.ToString());

2 Comments

Can't you use just codeBlock.Replace("<DIST_N>", 0)?
I agree, but the answer was more in line with the original OP. string replace would have been sufficient here. May be i could add it as comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.