Jad Chahine
Jad Chahine

Reputation: 7149

C# RegExp Indentation and Line Break

I'm trying to insert an indented code inside another indented code, using the first indentation as base for the second.

I mean, the second indentation must begin at the end of the first.

The indentation i got working right, but it is adding some undesired line breaks, that i need to avoid.

Here is the example for the code, i won't post the actual code because the strings are build dynamically and some i got from text files.

So i split it up and put it together for easy understanding.

STRING TO REPLACE WITH

<div class="form-item">
    <div class="form-item-label inline" ><span></span></div>
    <input type="text" value="" >
</div>

STRING WHERE REPLACING IN

<div id="formFiltro" class="form-filtro">
    <fieldset>
        <legend>Filtros</legend>

        <-'REPLACE_HERE'->

    </fieldset>
</div>

DESIRED RESULT

<div id="formFiltro" class="form-filtro">
    <fieldset>
        <legend>Filtros</legend>

        <div class="form-item">
            <div class="form-item-label inline" ><span></span></div>
            <input type="text" value="" >
        </div>

    </fieldset>
</div>

MY ATTEMPT

// newCode = string to replace with
// code = string where replacing

string pattern = "\r\n|\r|\n"; // Replace line breaks with "$1" to be used on the second replace

newCode = Regex.Replace( newCode, pattern, @"$1" );

pattern = @"([\s\t]*)(<-'REPLACE_HERE'->)"; //Copy default identation for new code while keeping "<-'REPLACE_HERE'->" on the original position

code = Regex.Replace(codigo, pattern, String.Format(@"$1$2$1{0}", newCode));

WHAT I GOT

<div id="formFiltro" class="form-filtro">
    <fieldset>
        <legend>Filtros</legend>

        <div class="form-item">

            <div class="form-item-label inline" ><span></span></div>

            <input type="text" value="" >

        </div>

    </fieldset>
</div>

Thanks in advance.

Upvotes: 0

Views: 138

Answers (1)

buckley
buckley

Reputation: 14079

You'll need to do some more C#ing but regex can help.

First match the characters that are in front of your placeholder

(.*?)<-'REPLACE_HERE'->

Your match will be in group 1

Then process the replacement text by prefixing it for each line

resultString = Regex.Replace(subjectString, "^(.*)$", "MatchedTextFromPrefiousRegex$1", RegexOptions.Multiline);

Then make the actual replacement.

Upvotes: 1

Related Questions