Looking for the longest interlinear regular expression?

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

public static Regex pattern2 = new Regex("[a-zA-Z]"); public static string zad3 = "ala123alama234ijeszczepsa"; 
+5
source share
6 answers

You can iterate 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; 
+5
source

Using linq and short:

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

Try the following:

  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(); 
+1
source

The best solution for your task:

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

You must modify the Regex template to include the repeat operator + so that it matches more than once.

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

You can get the longest value with LINQ. Order by the length of the match, and then take the first entry. If there are no matches, the result will be 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; 

A string named result in this example:

ijeszczepsa

+1
source

you can find it in O (n), like this (if you don't want to use the 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); 
-1
source

Source: https://habr.com/ru/post/1274440/


All Articles