我正在尝试解析一系列项目,使用Sprache库进行C#我有一个像这样的工作代码。
public static Parser<string> Array =
from open in OpenBrackets.Named("open bracket")
from items in Literal.Or(Identifier).Or(Array).DelimitedBy(Comma).Optional()
from close in CloseBrackets.Named("close bracket")
select open + (items.IsDefined ? string.Join(", ", items.Get()) : " ") + close;
其中“Literal”是数字或字符串的解析器,“Identifier”是变量标识符的解析器,“Comma”是逗号标记的解析器。但是如果我希望数组允许为空“[]”我需要添加Optional()属性并验证是否定义了“items”:
select open + (items.IsDefined ? string.Join(", ", items.Get()) : " ") + close;
是否有更好的清洁方法来解析由分隔符char分隔的项目列表,该列表可以为空(列表)。我可以重复使用其他项目列表。
输入数据结构示例:
[Literal/Identifier/Array] => Value;
[Value] [,Value]* => Array
[public/private] [identifier]; => Declaration;
[public/private] [identifier] [[=] [Value]] => Initialization;
答案 0 :(得分:2)
可以使用GetOrElse
方法来实现一种更简洁的方法。
select open + string.Join(", ", items.GetOrElse(new string[0])) + close;
答案 1 :(得分:0)
尝试使用Regex,如下面的代码所示:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
string pattern = @"\[(?'bracketData'[^\]]+)\](?'repeat'[*+])?";
string line = "";
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (line.Length > 0)
{
string suffix = line.Split(new string[] {"=>"}, StringSplitOptions.None).Select(x => x.Trim()).Last();
MatchCollection matches = Regex.Matches(line, pattern);
var brackets = matches.Cast<Match>().Select(x => new { bracket = x.Groups["bracketData"].Value, repeat = x.Groups["repeat"].Value }).ToArray();
Console.WriteLine("Brackets : '{0}'; Suffix : '{1}'", string.Join(",", brackets.Select(x => "(" + x.bracket + ")" + x.repeat )), suffix);
}
}
Console.ReadLine();
}
}
}