【问题标题】:C# RegExp Indentation and Line BreakC# RegEx 缩进和换行
【发布时间】:2015-08-14 12:26:14
【问题描述】:

我正在尝试在另一个缩进代码中插入一个缩进代码,使用第一个缩进作为第二个缩进的基础。

我的意思是,第二个缩进必须从第一个缩进的末尾开始。

我的缩进工作正常,但它添加了一些我需要避免的不需要的换行符。

这是代码示例,我不会发布实际代码,因为字符串是动态构建的,有些是从文本文件中获取的。

为了便于理解,我将其拆分并放在一起。

要替换的字符串

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

替换的字符串

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

        <-'REPLACE_HERE'->

    </fieldset>
</div>

期望的结果

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

我的尝试

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

我得到了什么

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

提前致谢。

【问题讨论】:

  • 所以,您希望我们修复您的正则表达式,但您不打算发布您的正则表达式?大问!

标签: c# asp.net regex


【解决方案1】:

您需要做更多的 C#ing,但正则表达式可以提供帮助。

首先匹配占位符前面的字符

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

你的比赛将在第 1 组

然后通过为每一行添加前缀来处理替换文本

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

然后进行实际替换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多