简体   繁体   中英

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";

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;

Using linq and the short one:

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

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();

best solution for your task is:

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM