0

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.

0

2 Answers 2

1

Try this way:

string result = (new Regex("\/\/BEGIN:(.|\n)*\/\/END:"))
    .Replace(text, Environment.NewLine);
Sign up to request clarification or add additional context in comments.

Comments

0

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);

1 Comment

This worked like a charm, just had to implement a counting function so it keeps deleting the multiple section's that start with //BEGIN: Thank you very much!

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.