[英]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>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.