iT邦幫忙

4

【C#、Regex】像 #if DEBUG and #endif 刪除指定内容

c#

最近想發布 SQL Script 檔案到正式環境時,自動將 Dev 測試腳本部分移除
嘗試卡住發問在S.O得到 Nick 解答 c# - How like '#if DEBUG' and '#endif' remove content between two marks - Stack Overflow

舉例:
有一個 A.sql 內容:

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

想變成

select 
    id
    ,name

from table
where sDate >= '2021-01-01'

可以這樣做

void Main()
{
	var input = @"
select 
    id
    ,name
    /**if DEBUG**/
    ,test1
    ,test2
    /**endif**/
from table
where sDate >= '2021-01-01'
    /**if DEBUG**/
    and test1 = '123456'
	and test2 = '123456'
    /**endif**/            
            ";
	var output = Regex.Replace(input, @"/\*\*if\sDEBUG\*\*/.*?/\*\*endif\*\*/", "", RegexOptions.Singleline);
	Console.WriteLine(output);
}

注意:特別使用 RegexOptions.Singleline 因為它將整個輸入字符串視為一行,忽略了換行符。

覺得有幫助可以幫 Nick 點個 Upvote ^__^


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言