找到最长的子串正则表达式?

问题描述 投票:5回答:6

有人知道如何使用MatchCollection找到由字母组成的最长子字符串。

public static Regex pattern2 = new Regex("[a-zA-Z]");
public static string zad3 = "ala123alama234ijeszczepsa";
c# regex algorithm
6个回答
5
投票

你可以遍历所有比赛并获得最长的比赛:

string max = "";

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

1
投票

试试这个:

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

或更好的方式:

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

1
投票

您的任务的最佳解决方案是:

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

1
投票

您必须更改正则表达式模式以包含重复运算符+,以使其匹配多次。

[a-zA-Z]应该是[a-zA-Z]+

您可以使用LINQ获得最长的值。按匹配长度降序排序,然后取第一个条目。如果没有匹配,结果是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;

在此示例中名为result的字符串是:

ijeszczepsa


1
投票

使用linq和短的:

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

-1
投票

你可以在O(n)中找到它(如果你不想使用正则表达式):

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);
© www.soinside.com 2019 - 2024. All rights reserved.