简体   繁体   中英

How like '#if DEBUG' and '#endif' remove content between two marks

How like '#if DEBUG' and '#endif' remove content between two marks

Eg: Below SQL string expect like '#if DEBUG' and '#endif' to remove string between /**if DEBUG**/ and /**endif**/

select
    id
    ,name
    /**if DEBUG**/
    ,test1
    ,test2
    /**endif**/
from table
where sDate >= '2021-01-01'
    /**if DEBUG**/
    and test1 = '123456'
    /**endif**/

expected result:

select
    id
    ,name
from table
where sDate >= '2021-01-01'

What I've tried

I tried use regex

  1. (\/\*\*if\sDEBUG\*\*\/)(?<content>)(\/\*\*endif\*\*\/)
  2. (\/\*\*if\sDEBUG\*\*\/)|(\/\/[\w\s\']*)|(\/\*\*endif\*\*\/)

to get string but not work, my code:

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,@"(\/\*\*if\sDEBUG\*\*\/)(?<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);   
}

Why not just use Regex.Replace directly? Note that you can use .*? to capture the text between the debug markers as long as you use RegexOptions.Singleline to make . match a newline:

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, @"/\*\*if\sDEBUG\*\*/.*?/\*\*endif\*\*/", "", RegexOptions.Singleline);
    Console.WriteLine(input);   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM