Reputation: 1520
I have a string that contain the following text:
[l=9;f=0;r=5;p=2]
There may be more than one:
[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]
I want to get the array of strings(for second example):
[l=9;f=0;r=5;p=2]
[l=9;f=0;r=6;p=2]
I tried this but it split not correctly:
Regex.Split(seat, "(?=])");
PS. regexp not mandatory.
Upvotes: 1
Views: 238
Reputation: 95242
In your code:
Regex.Split(seat, "(?=])");
Seems like you're just missing the actual semicolon, and a backslash for the brakcet, from your regex. This works:
string[] data = Regex.Split(seat, ";(?=\\[)");
Upvotes: 0
Reputation: 117029
Here's a LINQ approach:
Func<string, string> process = s =>
String.Format("[{0}]",
String.Join("];[",
s
.Split('[')
.Select(x => x.Split(']'))
.SelectMany(x => x)
.Where(x => x != "" && x !=";")));
At the very least it works. :-)
Use it like this:
var result = process("[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]");
Upvotes: 0
Reputation: 3138
The below pattern might help you use the Split option of Regex
string input = "[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]";
string pattern = @"(?<=\]);";
Regex regex = new Regex(pattern);
string[] data = regex.Split(input);
Upvotes: 3
Reputation: 5912
Why don't you use regex capturing?
The pattern \[l=(\d);f=(\d);r=(\d);p=(\d)\]
will capture the values in each array.
Example:
private static IEnumerable<dynamic> Match(string text)
{
return Regex.Matches(text, @"\[l=(\d);f=(\d);r=(\d);p=(\d)\]")
.Cast<Match>()
.Where(m => m.Success)
.Select(m => new { l = m.Groups[1].Value, f = m.Groups[2].Value, r = m.Groups[3].Value, p = m.Groups[4].Value });
}
static void Main(string[] args)
{
foreach (var result in Match("[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]"))
Console.Out.WriteLine("Setting: {0}, {1}, {2}, {3}", result.l, result.f, result.r, result.p);
foreach (var result in Match("[l=9;f=0;r=5;p=2]"))
Console.Out.WriteLine("Setting: {0}, {1}, {2}, {3}", result.l, result.f, result.r, result.p);
}
Upvotes: 0
Reputation: 116108
string input = "[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]";
var list = Regex.Matches(input, @"\[.+?\]")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
Upvotes: 8
Reputation: 9660
"[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]".Split(new string[] { "];" }, StringSplitOptions.None)
And then append "]" back to each item in the array...
Ugly but should work.
Upvotes: 0