Markdown表TestRail的Reqex

时间:2019-05-02 08:02:45

标签: c#

我找不到这种Markdown表的Regex解决方案。表语法用于TestRail表。

  1. 如何验证表格?
  2. 如何获取值?

表的格式可以如下:

||| :Page | :Option      | :Value | :Error Range
|| Page 1 | Page Margin  | 2cm    | 0.5cm 
|| Page 2 | Zoom Percent | 120%   | 0
|| Page 3 | Tab Depth    | 5      | 4-6 
|| Page 4 | Type Speed   | 20     | 15-25 

The first line specifies the table header and column alignments. The alignments are determined by colon characters in the respective header cells at the beginning/end of the cells. The following alignments are supported:

:Header Left-aligned (default)
:Header:    Centered
Header: Right-aligned

更新

我的解决方案如下:

  public static DataTable Gettable(string inputtable)
        {
            // validate header
            string patternheader = @"^(\|\|\|[^\n]+\r?\n)";
            string patternrow = @"^(\|\|[^\n])";

            // validate header
            var result = Regex.Matches(inputtable, patternheader);
            if (result.Count < 1)
                return null;

            // split into lines 
            string[] lines = inputtable.Split(
                new[] { Environment.NewLine },
                StringSplitOptions.RemoveEmptyEntries
            );

            // get headernames and clean
            var headernames = lines[0].Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Select(s => s.Trim().Replace(":", ""));

            // add headernames to table
            DataTable dt = new DataTable();
            foreach (var headername in headernames)
            {
                dt.Columns.Add(headername);
            }

            // validate and fill datatable with data
            for (int i = 1; i < lines.Length; i++)
            {
                // validate row 
                result = Regex.Matches(lines[i], patternrow);
                if (result.Count < 1)
                    return null;
                // get rowdata
                string[] rowdatas = lines[i].Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                    .Where(x => !string.IsNullOrWhiteSpace(x))
                    .Select(s => s.Trim()).ToArray();
                // add rowdata to databale row
                dt.Rows.Add(rowdatas);
            }
            return dt;
        }

更新II:

该表位于json响应内部,如下所示。

string table = "||| :Page | :Option      | :Value | :Error Range\r\n" +
                "|| Page 1 | Page Margin  | 2cm    | 0.5cm \r\n" +
                "|| Page 2 | Zoom Percent | 120%   | 0\r\n" +
                "|| Page 3 | Tab Depth    | 5      | 4-6 \r\n" +
                "|| Page 4 | Type Speed   | 20     | 15-25 \r\n";

0 个答案:

没有答案