RegExp缩进和换行
本文关键字:换行 缩进 RegExp | 更新日期: 2023-09-27 18:07:53
我试图在另一个缩进代码中插入缩进代码,使用第一个缩进作为第二个缩进的基础。
我的意思是,第二次缩进必须在第一次缩进的末尾开始。
缩进我得到了正确的工作,但它增加了一些不需要的换行符,我需要避免。
这里是代码的例子,我不会发布实际的代码,因为字符串是动态构建的,有些我从文本文件中得到。
所以我把它们分开放在一起,以便于理解。
要用 替换的字符串
<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));
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>
你需要做更多的c#,但正则表达式可以帮助。
首先匹配占位符
前面的字符(.*?)<-'REPLACE_HERE'->
你的比赛将在第1组
然后通过为每行
添加前缀来处理替换文本resultString = Regex.Replace(subjectString, "^(.*)$", "MatchedTextFromPrefiousRegex$1", RegexOptions.Multiline);
然后进行实际替换