打印IEnumerable作为从Regex.Matches收到的字符串

时间:2016-06-28 00:00:02

标签: c#

所以我有一个以下代码来匹配RegEx模式。

string data = "1463735418 Bytes: 0 Time: 4.297 1463735424 Time: 2.205 1466413696 Time: 2.225 1466413699 1466413702 1466413705 1466413708 1466413711 1466413714 1466413717 1466413720 Bytes: 7037 Time: 59.320 ......";

string pattern = @"
    (?<=Bytes:\s)(?<Bytes>\d+)   # Lookbehind for the bytes
    |                            # Or
    (?<=Time:\s)(?<Time>[\d.]+)  # Lookbehind for time
    |                            # Or
    (?<Integer>\d+)              # most likely its just an integer.
    ";

Regex.Matches(data, pattern, RegexOptions.IgnorePatternWhitespace)
     .OfType<Match>()
     .Select(mt => new
                   {
                       IsInteger = mt.Groups["Integer"].Success,
                       IsTime = mt.Groups["Time"].Success,
                       IsByte = mt.Groups["Bytes"].Success,
                       strMatch = mt.Groups[0].Value,
                       AsInt  = mt.Groups["Integer"].Success ? int.Parse(mt.Groups["Integer"].Value) : -1,
                       AsByte = mt.Groups["Bytes"].Success ? int.Parse(mt.Groups["Bytes"].Value) : -1,
                       AsTime = mt.Groups["Time"].Success ? double.Parse(mt.Groups["Time"].Value) : -1.0,
                   })  

如何将其作为字符串打印出来,即来自RegEx的匹配数据?

也就是说,我需要我的结果即。 as string:

Expected Output: 
0, 4.297 
7037, 59.320
...

感谢。

2 个答案:

答案 0 :(得分:2)

查看您的示例我假设您只想匹配“字节:x时间:y”以便输出。

你可以通过这种方式轻松实现:

        string pattern = @"
                        Bytes:\s
                        (?<Bytes>\d+)
                        \s+
                        Time:\s
                        (?<Time>[\d.]+)";

        var matches = Regex.Matches(data, pattern, RegexOptions.IgnorePatternWhitespace)
             .OfType<Match>()
             .Select(mt => mt.Groups["Bytes"] + " " + mt.Groups["Time"]);

        string result = String.Join("\n", matches);

否则,您可以将Regex.Matches()中的MatchCollection存储在变量中,并分别运行两个linq表达式

答案 1 :(得分:2)

如果你可以避免使用正则表达式,那么这里有一个替代方案:

var results =
    lines
        .Zip(lines.Skip(1), (l0, l1) => l0.Split(':').Concat(l1.Split(':')).ToArray())
        .Where(x => x[0] == "Bytes" && x[2] == "Time")
        .Select(x => $"{int.Parse(x[1].Trim())}, {double.Parse(x[3].Trim())}");

假设您的数据与之前的问题类似:

1463735418
Bytes: 0
Time: 4.297
1463735424
Time: 2.205
1466413696
Time: 2.225
1466413699
1466413702
1466413705
1466413708
1466413711
1466413714
1466413717
1466413720
Bytes: 7037
Time: 59.320

这给出了预期的结果:

0, 4.297 
7037, 59.32