Efratror
Efratror

Reputation: 31

Select Text in a File and replace it using C#

I want to replace a section of text in a file the section should start with //BEGIN: and end with //END:

the replacement is just a black line,

this is the code i use:

text = Regex.Replace(text, @"//(.*?)\r?\n", me =>
{
    bool x = false;
    if (me.Value.StartsWith("//BEGIN:"))
    {
        x = true;
        return me.Value.StartsWith("//BEGIN:") ? Environment.NewLine : "";
    }
    if (x == true)
    {
        return Environment.NewLine;
    }
    if (me.Value.StartsWith("//END:"))
    {
        x = false;
        return me.Value.StartsWith("//END:") ? Environment.NewLine : "";
    }
    return me.Value;
}, RegexOptions.Singleline);

but it isn't working like i want to.

Upvotes: 0

Views: 76

Answers (2)

Gilad Green
Gilad Green

Reputation: 37299

Try this way:

string result = (new Regex("\/\/BEGIN:(.|\n)*\/\/END:"))
    .Replace(text, Environment.NewLine);

Upvotes: 1

Zein Makki
Zein Makki

Reputation: 30022

Without the overhead of Regex and pattern matching, you can try this simple solution:

int start = text.IndexOf("//BEGIN");
int end = text.IndexOf("//END");

if(start >= 0 && end >=0 && end > start)
    text = text.Substring(0, start) + Environment.NewLine + text.Substring(end + "//END".Length);

Upvotes: 0

Related Questions