簡體   English   中英

解析以下文本的最有效方法

[英]Most efficient way to parse the following text

給定以下輸入

@class using System.Text.Json
@attribute using System
@attribute using System.Text
@attribute required Type theType
@attribute optional bool IsReadOnly = false
@attribute optional bool SomethingElse

我需要創建以下對象

  new UsingClause(Target.Class, "System.Text.Json");
  new UsingClause(Target.Attribute, "System");
  new UsingClause(Target.Attribute, "System.Text");
  new AttributeProperty(required: true, name: "theType", type: "Type", default: null);
  new AttributeProperty(required: false, name: "IsReadOnly", type: "bool", default: "true");
  new AttributeProperty(required: false, name: "SomethingElse", type: "bool", default: null);

通常我會用空格將字符串分割成一個數組等,但這將用於 Roslyn 代碼生成器,所以我需要它盡可能快。

對於這種腳本預處理任務,我應該使用什么方法?

我已經開始使用StringReader讀取每一行,然后使用已編譯的Regex檢查它。 但是這整個“超高效”要求對我來說是新的,我不想冒險搞砸它。

    private readonly static Regex Regex = new Regex(
      pattern: @"^\s*((@attribute)\s+(using)\s+(.*))|((@attribute)\s+(optional|required)\s+(\w+[\w\.]*)\s+(\w+)(\s*\=\s*(.*))?)|((@class)\s+(using)\s+(.*))\s*$",
      options: RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);

這有點取決於您認為“高效”的內容,但您應該考慮編寫一個 ANTLR 語法,該語法允許將文本解析為 C# 對象,然后您可以使用 Antlr4.Runtime.Standard 之類的東西將其轉換為所需的output 對象

編寫 ANTLR 語法有助於發現輸入“語言”中的任何不一致/歧義。 它還允許您在將來添加/更改功能。

暫無
暫無

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

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