Sumit Roy
Sumit Roy

Reputation: 423

Remove multiple occurrences between characters in string

string Test = "SET @rhsLclGrpVar = CAST(@variable1 AS CHAR(3)) /*RHS: X(03)*/+ 
CAST(@variable2 AS CHAR(42)) /*RHS: X(42)*/+ CAST(@variable3 AS 
CHAR(8)) /*RHS: X(08)*/";

I want to remove anything that comes between

"/*" and "*/"

For single occurence I have a code like :

int startIndex = item.IndexOf("/*");
int endIndex = item.LastIndexOf("*/");
string Output = item.Replace(item.Substring(startIndex, endIndex - 
startIndex + 2), string.Empty));

This works fine in case of single occurrence.

Upvotes: 2

Views: 1000

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477853

You can use a regex for that:

Regex rgx = new Regex(@"/\*.*?\*/");
string output = rgx.Replace(item,"");

When running this in the csharp interactive console, we get:

csharp> using System.Text.RegularExpressions; 
csharp> string item = "SET @rhsLclGrpVar = CAST(@variable1 AS CHAR(3)) /*RHS: X(03)*/+ CAST(@variable2 AS CHAR(42)) /*RHS: X(42)*/+ CAST(@variable3 AS CHAR(8)) /*RHS: X(08)*/"; 
csharp> Regex rgx = new Regex(@"/\*.*?\*/");                                                                                                                                    
csharp> rgx.Replace(item,"");                                                                                                                                                    
"SET @rhsLclGrpVar = CAST(@variable1 AS CHAR(3)) + CAST(@variable2 AS CHAR(42)) + CAST(@variable3 AS CHAR(8)) " 

The regex works as follows: the /\* part simply recognizes the /* pattern. Next the .*? matches non-greedy any sequence of characters, but will cut-off from the moment it matches the next part of the pattern, the \*/ which is the */ fragment. By using Replace we replace all matches of that pattern with the empty string, thus we remove it.

A solution using IndexOf could be:

string result = item;
while(true) {
    idx = result.indexof("/*");
    if(idx >= 0) {
        idx2 = result.indexof("*/",idx);
        if(idx2 >= 0) {
            result = result.Substring(0,idx)+result.Substring(idx2+2);
        }
    } else {
        break;
    }
}

But this is quite complex (with some chance of still having some bugs) and will probably be less efficient.

Upvotes: 3

Related Questions