-3

I'm currently thinking of how to split this kind of string into regex using c#.

[01,01,01][02,03,00][03,07,00][04,06,00][05,02,00][06,04,00][07,08,00][08,05,00]

Can someone knowledgeable on regex can point me on how to achieved this goal?

sample regex pattern that don't work:

[\dd,\dd,\dd]

sample output:

[01,01,01]
[02,03,00]
[03,07,00]
[04,06,00]
[05,02,00]
[06,04,00]
[07,08,00]
[08,05,00]
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
iamcoder
  • 529
  • 2
  • 4
  • 23

4 Answers4

3

This will do the job in C# (\[.+?\]), e.g.:

var s = @"[01,01,01][02,03,00][03,07,00][04,06,00][05,02,00][06,04,00][07,08,00][08,05,00]";
var reg = new Regex(@"(\[.+?\])");
var matches = reg.Matches(s);
foreach(Match m in matches)
{
    Console.WriteLine($"{m.Value}");
}

EDIT This is how the expression (\[.+?\]) works

  1. first the outter parenthesis, ( and ), means to capture whatever the inside pattern matched
  2. then the escaped square brackets, \[ and \], is to match the [ and ] in the source string
  3. finally the .+? means to match one or more characters, but as few times as possible, so that it won't match all the characters before the first [ and the last ]
Evan Huang
  • 1,245
  • 9
  • 16
3

I know you stipulated Regex, however it's worth looking at Split again, if for only for academic purposes:

Code

var input = "[01,01,01][02,03,00][03,07,00][04,06,00][05,02,00][06,04,00][07,08,00][08,05,00]";

var output = input.Split(']',StringSplitOptions.RemoveEmptyEntries)
                     .Select(x  => x + "]") // the bracket back
                     .ToList();

foreach(var o in output) 
   Console.WriteLine(o);

Output

[01,01,01]
[02,03,00]
[03,07,00]
[04,06,00]
[05,02,00]
[06,04,00]
[07,08,00]
[08,05,00]
halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
1

The Regex solution below is restricted to 3 values of only 2 digits seperated by comma. Inside the foreach loop you can access the matching value via match.Value.

Remember to include using System.Text.RegularExpressions;

var input = "[01,01,01][02,03,00][03,07,00][04,06,00][05,02,00][06,04,00][07,08,00][08,05,00]";
foreach(var match in Regex.Matches(input, @"(\[\d{2},\d{2},\d{2}\])+"))
{
  // do stuff
}
Thom A
  • 88,727
  • 11
  • 45
  • 75
Jules
  • 567
  • 1
  • 6
  • 15
0

Thanks all for the answer i also got it working by using this code

string pattern = @"\[\d\d,\d\d,\d\d]";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

MatchCollection matches = rgx.Matches(myResult);

Debug.WriteLine(matches.Count);

foreach (Match match in matches)
   Debug.WriteLine(match.Value);
iamcoder
  • 529
  • 2
  • 4
  • 23