Karol Pisarzewski
Karol Pisarzewski

Reputation: 700

Finding the longest substring regex?

Someone knows how to find the longest substring composed of letters using using MatchCollection.

public static Regex pattern2 = new Regex("[a-zA-Z]");
public static string zad3 = "ala123alama234ijeszczepsa";

Upvotes: 5

Views: 3114

Answers (6)

OmG
OmG

Reputation: 18838

Using linq and the short one:

string longest= Regex.Matches(zad3, pattern2).Cast<Match>()
.OrderByDescending(x => x.Value.Length).FirstOrDefault()?.Value;

Upvotes: 1

Equalsk
Equalsk

Reputation: 8214

You must change your Regex pattern to include the repetition operator + so that it matches more than once.

[a-zA-Z] should be [a-zA-Z]+

You can get the longest value using LINQ. Order by the match length descending and then take the first entry. If there are no matches the result is null.

string pattern2 = "[a-zA-Z]+";
string zad3 = "ala123alama234ijeszczepsa";

var matches = Regex.Matches(zad3, pattern2);

string result = matches
                 .Cast<Match>()
                 .OrderByDescending(x => x.Value.Length)
                 .FirstOrDefault()?
                 .Value;

The string named result in this example is:

ijeszczepsa

Upvotes: 2

Leon Barkan
Leon Barkan

Reputation: 2703

best solution for your task is:

string zad3 = "ala123alama234ijeszczepsa54dsfd";
string max = Regex.Split(zad3,@"\d+").Max(x => x);

Upvotes: 1

Aria
Aria

Reputation: 3844

Try this:

 MatchCollection matches = pattern2.Matches(txt);
 List<string> strLst = new List<string>();
 foreach (Match match in matches)
     strLst.Add(match.Value);
 var maxStr1 = strLst.OrderByDescending(s => s.Length).First();

or better way :

 var maxStr2 = matches.Cast<Match>().Select(m => m.Value).ToArray().OrderByDescending(s => s.Length).First();

Upvotes: 1

user9150053
user9150053

Reputation:

you can find it in O(n) like this (if you do not want to use regex):

string zad3 = "ala123alama234ijeszczepsa";
int max=0;
int count=0;
for (int i=0 ; i<zad3.Length ; i++)
{
    if (zad3[i]>='0' && zad3[i]<='9')
    {   
        if (count > max)
            max=count;
        count=0;
        continue;
    }
    count++;                
}

if (count > max)
    max=count;

Console.WriteLine(max);

Upvotes: -1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

You can loop over all matches and get the longest:

string max = "";

foreach (Match match in Regex.Matches(zad3, "[a-zA-Z]+"))
    if (max.Length < match.Value.Length)
        max = match.Value;

Upvotes: 5

Related Questions