Reputation: 3304
I'm getting a string with some patterns, like:
A 11 A 222222 B 333 A 44444 B 55 A 66666 B
How to get all the strings between A and B in the smallest area?
For example, "A 11 A 222222 B" result in " 222222 "
And the first example should result in:
222222
333
44444
55
66666
Upvotes: 0
Views: 65
Reputation: 521259
We can try searching for all regex matches in your input string which are situated between A
and B
, or vice-versa. Here is a regex pattern which uses lookarounds to do this:
(?<=\bA )\d+(?= B\b)|(?<=\bB )\d+(?= A\b)
Sample script:
string input = "A 11 A 222222 B 333 A 44444 B 55 A 66666 B";
var vals = Regex.Matches(input, @"(?<=\bA )\d+(?= B\b)|(?<=\bB )\d+(?= A\b)")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
foreach (string val in vals)
{
Console.WriteLine(val);
}
This prints:
222222
333
44444
55
66666
Upvotes: 5