'#ifDEBUG'和'#endif'如何删除两个标记之间的内容
c#
'#if DEBUG' 和 '#endif' 如何删除两个标记之间的内容
例如:在 SQL 字符串下面期望像 '#if DEBUG' 和 '#endif' 来删除/**if DEBUG**/和/**endif**/
select
id
,name
/**if DEBUG**/
,test1
,test2
/**endif**/
from table
where sDate >= '2021-01-01'
/**if DEBUG**/
and test1 = '123456'
/**endif**/
预期结果 :
select
id
,name
from table
where sDate >= '2021-01-01'
我试过的
我试过使用正则表达式
(/**ifsDEBUG**/)(?<content>)(/**endif**/)(/**ifsDEBUG**/)|(//[ws']*)|(/**endif**/)
要获取字符串但不起作用,我的代码:
void Main()
{
var input = @"
select
id
,name
/**if DEBUG**/
,test1
,test2
/**endif**/
from table
where sDate >= '2021-01-01'
/**if DEBUG**/
and test1 = '123456'
/**endif**/
";
var matchs = Regex.Matches(input,@"(/**ifsDEBUG**/)(?<content>)(/**endif**/)")
.Select(m=>new {Key = m.Groups["content"].Value,Value=m.Groups["content"].Value})
;
foreach (var m in matchs)
{
input.Replace(m.Value,"");
}
Console.WriteLine(input);
}
回答
为什么不直接使用Regex.Replace呢?请注意,.*?只要您使用RegexOptions.Singlelinemake .match 换行符,您就可以使用捕获调试标记之间的文本:
void Main()
{
var input = @"
select
id
,name
/**if DEBUG**/
,test1
,test2
/**endif**/
from table
where sDate >= '2021-01-01'
/**if DEBUG**/
and test1 = '123456'
/**endif**/
";
input = Regex.Replace(input, @"/**ifsDEBUG**/.*?/**endif**/", "", RegexOptions.Singleline);
Console.WriteLine(input);
}