簡體   English   中英

在文本中查找注釋並使用Regex替換它們

[英]Find comments in text and replace them using Regex

我目前使用File.ReadAllLines來獲取所有源文件並閱讀他們的文本,我想用一個正則表達式過濾所有注釋。 基本上所有評論可能性。 我嘗試了幾種在互聯網上找到的正則表達式解決方案。 就像這個:

@"(@(?:""[^""]*"")+|""(?:[^""\\n\\\\]+|\\\\.)*""|'(?:[^'\\n\\\\]+|\\\\.)*')|//.*|/\\*(?s:.*?)\\*/"

當我谷歌時,最好的結果:

string blockComments = @"/\*(.*?)\*/";
string lineComments = @"//(.*?)\r?\n";
string strings = @"""((\\[^\n]|[^""\n])*)""";
string verbatimStrings = @"@(""[^""]*"")+";

請參閱:正則表達式從C#中刪除行注釋

第二種解決方案不會識別任何評論。

這就是我目前所做的

public static List<string> FormatList(List<string> unformattedList, string dataType)
{
    List<string> formattedList = unformattedList;

    string blockComments = @"/\*(.*?)\*/";
    string lineComments = @"//(.*?)\r?\n";
    string strings = @"""((\\[^\n]|[^""\n])*)""";
    string verbatimStrings = @"@(""[^""]*"")+";

    string regexCS = blockComments + "|" + lineComments + "|" + strings + "|" + verbatimStrings;
    //regexCS = @"(@(?:""[^""]*"")+|""(?:[^""\n\\]+|\\.)*""|'(?:[^'\n\\]+|\\.)*')|//.*|/\*(?s:.*?)\*/";
    string regexSQL = "";

    if (dataType.Equals("cs"))
    {
        for(int i = 0; i < formattedList.Count;i++)
        {
            string line = formattedList[i];
            line = line.Trim(' ');

            if(Regex.IsMatch(line, regexCS))
            {
                line = "";
            }

            formattedList[i] = line;
        }
    }
    else if(dataType.Equals("sql"))
    {

    }
    else
    {
        throw new Exception("Unknown DataType");
    }

    return formattedList;
}

第一個方法識別注釋,但也發現類似的東西

string[] bla = text.Split('\\\\');

有沒有解決這個問題的方法? 正則表達式排除了字符串/ char中的匹配? 如果您有任何其他鏈接我應該檢查,請告訴我!

我嘗試了很多,無法弄清楚為什么這對我不起作用。

[我也試過這些鏈接]

https://blog.ostermiller.org/find-comment

https://codereview.stackexchange.com/questions/167582/regular-expression-to-remove-comments

正則表達式在c#源文件中查找注釋

正如評論中所述,使用正則表達式執行此操作將非常困難。 但是,消除注釋的一種好方法是使用CSharpSyntaxWalker 語法行者知道所有語言結構,並且不會很難調查錯誤(正如正則表達式那樣)。

添加對Microsoft.CodeAnalysis.CSharp Nuget包的引用,並從CSharpSyntaxWalker繼承。

class CommentWalker : CSharpSyntaxWalker
{
    public CommentWalker(SyntaxWalkerDepth depth = SyntaxWalkerDepth.Node) : base(depth)
    {
    }

    public override void VisitTrivia(SyntaxTrivia trivia)
    {
        if (trivia.IsKind(SyntaxKind.MultiLineCommentTrivia)
            || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia))
        {
            // Do something with the comments
            // For example, find the comment location in the file, so you can replace it later.
            // Make a List as a public property, so you can iterate the list of comments later on.
        }
    }
}

然后你可以像這樣使用它:

// Get the program text from your .cs file
SyntaxTree tree = CSharpSyntaxTree.ParseText(programText);
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();

var walker = new CommentWalker();
walker.Visit(root);

// Now iterate your list of comments (probably backwards) and remove them.

進一步閱讀:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM