Archana
Archana

Reputation: 84

Get only the longest match from the groups in regex

I have various strings like '10001110110', '10000', '100001', '00011','0001', '111000' etc..

I need to find out the longest possible combination of 1s with no or 1 zero in between.

I have got a regex like this - (?=(1+01+))

But its not returning a group where there is no leading or trailing one.

I want to regex to consider this case too.

Currently its returning all groups Eg. if the input string is '10110111' it returns 3 groups

{null, 1011}, {null, 110111} and {null, 10111}

I want my regex to return only 1 match with the longest combination. Is it possible to do so?

Upvotes: 2

Views: 487

Answers (1)

The fourth bird
The fourth bird

Reputation: 163467

For the following rule:

I need to find out the longest possible combination of 1s with no or 1 zero in between.

you can capture 1+ times a 1, and then optionally match 0 followed by again 1+ times a 1 in the lookahead assertion.

(?=(1+(?:0?1+)?))

Regex demo | C# demo

To get the longest result, you can process the matches, and then sort by the length of the string, and then get the first result from the collection.

string pattern = @"(?=(1+(?:0?1+)?))";
string input = @"10001110110 10000 100001 00011 0001 111000 101110111011011";

var result = Regex.Matches(input, pattern)

.Select(m => m.Groups[1].Value)
.OrderByDescending(s => s.Length)
.FirstOrDefault();

Console.WriteLine(result);

Output

1110111

Upvotes: 2

Related Questions