繁体   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