在C#中使用Regex检查可选的逗号分隔重复序列

时间:2016-01-18 09:42:09

标签: c# regex

提前感谢所有帮助。

我对正则表达式很新,我发现它有点难以掌握。

我有一个WindowsForm C#,用户可以用逗号分隔格式输入一组数据作为单个字符串。数据也使用方括号()分组。

每个小组由

组成

(int type, int year, int age_start, int age_end)

在文本框中,用户可以输入多个组

(group1),(group2)

我设法获得了用于拆分组的正则表达式

Regex RejectStringRegex = new Regex(@"\(([^)]*)\)");

并拆分组中的数据(我刚刚意识到这可能没有考虑到文本中的空格)

Regex SubRejectStringRegex = new Regex(@"(\d+),(\d+),(\d+),(\d+)");

我能做的就是如何拒绝格式错误的组字符串,例如

(1,89,10,10),(

(1,14,10,10),(2,15,20,30),(10

执行检查的代码目前看起来像这样。请注意,我将regex检查分开,因为我使用它们将数据稍后处理为List<>但是如果将它作为一个进程更简单,那么我对此也很好。

private bool CheckForValidReject()
{
    bool StringValid = false;
    Regex RejectStringRegex = new Regex(@"\(([^)]*)\)");
    Regex SubRejectStringRegex = new Regex(@"(\d+),(\d+),(\d+),(\d+)");

    MatchCollection AllMatches = RejectStringRegex.Matches(tbRejectString.Text);

    if (AllMatches.Count > 0)
    {
        StringValid = true;
        foreach (Match SomeMatch in AllMatches)
        {
            Match RejectMatch = SubRejectStringRegex.Match(SomeMatch.Groups[0].Value);

            if (!RejectMatch.Success)
            {
                StringValid = false;
            }
        }
    }
    return StringValid;
}

N.B:在调用之前检查文本框是否为空字符串。

1 个答案:

答案 0 :(得分:0)

您可以使用

^\(\s*(?<type>\d+)\s*,\s*(?<year>\d+)\s*,\s*(?<agestart>\d+)\s*,(?<ageend>\d+)\s*\)\s*(,\s*\(\s*(?<type>\d+)\s*,\s*(?<year>\d+)\s*,\s*(?<agestart>\d+)\s*,(?<ageend>\d+)\s*\)\s*)*$

请参阅regex demo,与RegexOptions.ExplicitCapture标志一起使用。

enter image description here

在C#中,您需要获取组,然后通过Captures CaptureCollection访问所有值。

这是一个演示:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

// And then...

var strs = new List<string> { "(1,89,10,10)", "(1,14,10,10),(2,13,11,12)"};
var pattern = @"^\(\s*(?<type>\d+)\s*,\s*(?<year>\d+)\s*,\s*(?<agestart>\d+)\s*,(?<ageend>\d+)\s*\)\s*(,\s*\(\s*(?<type>\d+)\s*,\s*(?<year>\d+)\s*,\s*(?<agestart>\d+)\s*,(?<ageend>\d+)\s*\)\s*)*$";
foreach (var s in strs)
{
    var match = Regex.Match(s, pattern, RegexOptions.ExplicitCapture);  
    if (match.Success) 
    {
        Console.WriteLine(string.Join(", and ", match.Groups["type"].Captures.Cast<Capture>().Select(m => m.Value).ToList()));
        Console.WriteLine(string.Join(", and ", match.Groups["year"].Captures.Cast<Capture>().Select(m => m.Value).ToList()));
        Console.WriteLine(string.Join(", and ", match.Groups["agestart"].Captures.Cast<Capture>().Select(m => m.Value).ToList()));
        Console.WriteLine(string.Join(", and ", match.Groups["ageend"].Captures.Cast<Capture>().Select(m => m.Value).ToList()));
    }
}

请参阅IDEONE demo