簡體   English   中英

按字符串數組拆分字符串,並包含用於在C#中的最終數組中拆分的單詞

[英]Split string by array of strings, and include words used to split in final array in C#

我正在嘗試將字符串拆分為字符串數組中單詞周圍的數組。 現在,我正在使用myString.Split(arrayOfWordsToSplitOn, StringSplitOptions.RemoveEmptyEntries) ,它會分割字符串,但不包括要分割的實際單詞。

例如,如果我有字符串"My cat and my dog are very lazy"和字符串數組{"cat", "dog"} ,現在它返回{"My", "and my", "are very lazy"}

但是,我希望最終輸出為{"My", "cat", "and my", "dog", "are very lazy"} 有什么辦法嗎?

您可以從搜索詞列表中創建基於替代的正則表達式,然后用捕獲組(...)包裝該部分。 然后,添加\\s*Regex.Split組周圍的空白並使用Regex.Split

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var arrayOfWordsToSplitOn = new List<string> { "cat", "dog" };
        var s = "My cat and my dog are very lazy";
        var pattern = string.Format(@"\s*\b({0})\b\s*", string.Join("|", arrayOfWordsToSplitOn));
        var results = Regex.Split(s, pattern).Where(x => !String.IsNullOrWhiteSpace(x)).ToList();
        foreach (var res in results)
            Console.WriteLine(res);
    }
}

參見C#演示

結果:

My
cat
and my
dog
are very lazy

筆記:

  • 如果搜索詞可以包含非單詞字符,則應將模式調整為\\b (單詞邊界)可能會導致匹配失敗,並且搜索“單詞”必須為Regex.Escape d
  • 如果您決定放棄單詞邊界,則搜索單詞數組可能需要按長度和字母排序。

暫無
暫無

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

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