开发者

Regex, match varying number of sets

开发者 https://www.devze.com 2023-04-13 01:15 出处:网络
I have a program looking to capture formatted string input. The input looks something like {1, 2, 3, 4, 5, 6, 7}

I have a program looking to capture formatted string input. The input looks something like

{1, 2, 3, 4, 5, 6, 7}

Where there can be a varying number of numbers as long as they are all inside the set. For instance:

{1, 2, 3}
{1, 2, 3, 4}

Would all be valid. However, I need to be able to access each number within that set. I have the following code

Match match = Regex.Match(input, @"\{(\d,\s)*(\d)\}", RegexOptions.IgnoreCase);

if (match.Success)
{
    String s;

    for(int i = 0; i < match.Groups.Count; i++)
    {
        s = match.Groups[i]开发者_如何学JAVA.Value;
        // Do actions here
    }
}

Which matches fine, however, I can only access the last and next-to-last number within the set. I would like to be able to read the values from each member of the set. How would I go about doing this? Would something other than regex work better?


Would something other than regex work better?

While a regex would be most helpful for capturing the brace-enclosed strings, it would be easier after you get that to use simple imperative code to get the numbers within.

I would start with the regex \{([^\}]*)\} to grab the inner part of any string starting with '{' and ending with '}' (with no '}' in between). You can then process the capture using a split by commas to get the numbers within, trimming for whitespace afterwards if needed.


You should access the Captures property of the Group to access all captures.

for (int i = 0; i < match.Groups.Count; i++)
{
   CaptureCollection caps = match.Groups[i].Captures;
   foreach (Capture cap in caps)
   {
      Console.WriteLine(cap.Value);
   }
}

In addition, you might want to change your regex to for example "\{(\d)(?:,\s(\d))*\}" if you don't want the comma sign to be part of your captures and you want to also allow a set of only one number.


Try this:

var Input = "{1, 2, 3, 4, 5, 6, 7} foo {1, 2, 3} baa {1, 2, 3, 4} abc";
var Pattern = "\\{([0-9, ]+)\\}";
var Matches = Regex.Matches(Input, Pattern, RegexOptions.IgnorePatternWhitespace);
foreach (Match match in Matches)
{
    string s = match.Groups[1].Value; // n1,n2,n3.. 
     //do actions here 

    /* 
     * if you need parse each element,use s.Split(',').
     * For example 
     *      s is '1,2,3' 
     *      string[] parts = s.Split(',');
     *      for(int x = 0,max = parts.Length; x < max; x++) {
     *          Console.WriteLine(parts[x]);
     *      }
     *      
     *      the output is something like:
     *      1
     *      2
     *      3
     */

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号