簡體   English   中英

從字符串中提取 substring 列表並從字符串中刪除

[英]Extract list of substring from string and remove from string

我有一個字符串,必須提取 2 個不同單詞('alpha' 和 'beta')之間的所有子字符串。 我必須返回帶有兩個字段的 json。

我以這種方式嘗試過,但它不能正常工作:

            string content = "string working on";
            var listSubString = new List<string>();
            int index = 0;
            do
            {
                index = content.LastIndexOf("alpha");
                if (index != -1)
                {
                    var length = content.IndexOf("beta");
                    string substring= content.Substring(index, length);
                    content = content.Replace(substring, string.Empty);
                    listSubString.Add(substring.Replace("alpha", string.Empty).Replace("beta", string.Empty));
                }
            } while (index != -1);
Content = content;
ListSubString = listSubString;

我想要一個像"hello alpha I don't want this part 1 beta world alpha i don't want this part 2 beta have a nice day"這樣的字符串接收一個 json 像{Content: "hello world have a nice day, ListSubString: ["i don't want this part 1", "i don't want this part 2"]}

謝謝您的幫助

我得到了你想要的 output,希望它能解決你的目的

鏈接: https://dotnetfiddle.net/b8T8qy

我在您的代碼中更改了此代碼部分

string substring= content.Substring(index, length-1);
listSubString.Insert(0, substring.Replace("alpha", string.Empty).Replace("beta", string.Empty));

最后我將 output 結果附加為 json 字符串。

string json = string.Join("\",\"", listSubString);
string otp = "{\"Content\" : \""+content+"\",\"ListSubString\": [\""+json+"\"]}";

Output:

{
  "Content": "hello world have a nice day",
  "ListSubString": [
    " I don't want this part 1  ",
    " i don't want this part 2  "
  ]
}

正則表達式允許您在沒有索引和循環的情況下完成此操作。

一旦您確定了描述您要提取的子字符串的模式,例如"alpha.*?beta" ,那么在沒有所述子字符串的情況下重建內容只是連接由正則表達式拆分的片段的問題:

Content = string.Join(string.Empty, new Regex("alpha.*?beta").Split(text);

根據子字符串本身,您可以在模式中捕獲它們並從正則表達式返回的匹配中提取它們:

ListSubString = new Regex("alpha(.*?)beta")
    .Matches(text)
    .Select(match => match.Groups[1])
    .SelectMany(group => group.Captures.OfType<Capture>())
    .Select(capture => capture.Value)
    .ToList();

您可以查看此答案以了解有關Match > Group > Capture層次結構的一些說明。

感謝所有回復我的人。 最后,我決定這樣做:

var splitedContent = content.Split(new string[] { "alpha", "beta" }, StringSplitOptions.None);

Content = string.Join(" ", splitedContent.Where((_, index) => index % 2 == 0));
Css = splitedContent.Where((_, index) => index % 2 != 0).ToList<string>();

正則表達式可能是最好和最高效的解決方案,但我不明白它是如何完美運行的,所以目前這是我的解決方案。

暫無
暫無

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

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