2

I have the following string:

[Element][TOPINCLUDESAMEVALUES:5][ParentElement][ORDERBY:DateAdded]

and want to transform it to this:

[Element][TOP:5:WITHTIES][ParentElement][ORDERBY:DateAdded]

So, the [TOPINCLUDESAMEVALUES:5] is transform to [TOP:5:WITHTIES].

The input string could contain more [elements]. Each element is surrounded by square brackets []. For example:

...[element1][element2][TOPINCLUDESAMEVALUES:5]...[element3][element4][TOPINCLUDESAMEVALUES:105][element3]...

So, I need to transform each [TOPINCLUDESAMEVALUES:X] element to [TOP:X:WITHTIES] elements.

Generally, I try some combinations using regex replace substitutions but was not able to do it myself.

 string statement = "[Campaign][TOPINCLUDESAMEVALUES:5][InstanceID][GROUPBY:Campaign]";
 statement = Regex.Replace(statement, @"(?<=\[TOPINCLUDESAMEVALUES:)[^\]]+(?=\])", "");

Could anyone tell is there a way to do such replace?

1
  • Not knowing the load of data you'd be evaluating for replacement, but you might want to consider a manual replacement algorithm over regex for performance. Commented Jul 30, 2015 at 14:35

2 Answers 2

2

Since you are replacing the content of TOPINCLUDESAMEVALUES with something else, you need to capture it. Lookbehind that you are using is non-capturing, so you wouldn't be able to replace its content.

Here is how you should be able to do it:

statement = Regex.Replace(
    statement
,   @"\[TOPINCLUDESAMEVALUES:([^\]]+)\]", "[TOP:$1:WITHTIES]"
);

This expression would match the entire [TOPINCLUDESAMEVALUES:5] bracketed portion, and additionally capture 5 as capturing group number 1. The replacement value refers to that group as $1, pasting its content in between TOP: and :WITHTIES.

Demo.

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

Comments

0

try this

    string statement = "[Campaign][TOPINCLUDESAMEVALUES:5][InstanceID][GROUPBY:Campaign]";
    string[] arrstatement = "[Campaign][TOPINCLUDESAMEVALUES:5][InstanceID][GROUPBY:Campaign]".Split(']');
    for (int i = 0; i < arrstatement.Length; i++)
    {
        if (arrstatement[i].Contains("TOPINCLUDESAMEVALUES"))
            arrstatement[i] = "[TOP" + arrstatement[i].Substring(arrstatement[i].IndexOf(":")) + ":WITHTIES";
    }
    statement = string.Join("]", arrstatement);

Comments

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.