簡體   English   中英

如何在C#中使用Regex從一個字符串中提取多個子字符串

[英]How to use Regex in C# to extract multiple substrings from a string

我從網上搜索,我只有部分解決方案,所以我提出了這個問題。

輸入:

[A] this is A, and , [B] this is B, and hello , [C] this is C - From Here

我想要一個清單:

list[0] == "this is A, and"
list[1] == "this is B, and hello"
list[2] == "this is C"
list[3] == "From Here"

我發現我應該有這樣的東西:

Regex pattern = new Regex(@"^\[A\] (.*) , \[B\] (.*) , \[C\] (.*) - (.*)$");
List<string> matches = pattern.Matches(input).OfType<Mathc>().Select(m => m.value).Distinct().ToList();

但它不起作用。 我想問一下如何使它起作用。 謝謝。

正則表達式是正確的,您唯一需要做的就是迭代匹配組。 在您的情況下,第一組將是整個句子,因此,您可以簡單地跳過第一項。
PS ,當然不要忘記檢查是否至少顯示了一個匹配結果。 此外,如果此函數將被多次執行,我建議您將正則表達式提取到類的靜態成員中(因為性能和內存使用情況)。

private static readonly Regex pattern = new Regex(@"^\[A\] (.*) , \[B\] (.*) , \[C\] (.*) - (.*)$");

該方法的最終版本(以模式作為靜態成員)如下所示。

public static List<string> GetMatches(string input)
{
    var matchResult = pattern.Match(input);
    if (matchResult.Length > 0)
    {
        return matchResult.Groups.Values
            .Skip(1)
            .Select(x => x.Value)
            .ToList();
    }
    
    return new List<string>();
}

問題在於比賽和小組之間的混淆。 正則表達式只匹配一次,但里面有幾個組。 使用[0]訪問第一個匹配項,然后使用.OfType<Group>()

List<string> matches = pattern.Matches(input)[0].Groups.OfType<Group>().Select(m => m.Value).Distinct().ToList()

這會給你5個結果:

LinqPad 截圖

你可以用.Skip(1).Skip(1) matches.RemoveAt(0);去掉第一個matches.RemoveAt(0); .

暫無
暫無

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

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