0

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

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

Oh, sorry. I made a mistake. Can the result remove 11? I have edited the question. Thx.
What is the significance of removing 11? Is this a value which you want to remove anywhere in the array? Or, do you want to remove the first number of the array? Please explain.
I just want the strings between A and B matched in the smallest area. My input strings may like A..A.+.B..B..A..+..B...A..+..B..B. I just want +
@Vincent I fixed my answer. I missed the part about only picking up on matches between A..B or B..A.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.