簡體   English   中英

找到最長的子串正則表達式?

[英]Finding the longest substring regex?

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

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

你可以遍歷所有比賽並獲得最長的比賽:

string max = "";

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

使用linq和短的:

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

試試這個:

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

您的任務的最佳解決方案是:

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

您必須更改正則表達式模式以包含重復運算符+ ,以使其匹配多次。

[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

你可以在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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM