【问题标题】:How to get segments from a string? [closed]如何从字符串中获取段? [关闭]
【发布时间】:2017-07-13 14:50:48
【问题描述】:

我有一个包含我所有段的字符串。它看起来像这样:

var myString = "<seg_0 status=0>This is segment zero</seg_0><seg_1 status=1>This is segment one</seg_1><seg_2 status=0>This is segment two</seg_2>"

我想将我的字符串中的所有段都放入一个 ArrayList 中,如下所示:

{
 {"index":"0","status":"0","seg":"This is segment zero"},
 {"index":"1","status":"1","seg":"This is segment one"},
 {"index":"2","status":"0","seg":"This is segment two"}
}

如何使用 Regex 进行归档?

【问题讨论】:

  • 您应该先尝试解决问题,然后再返回具体帮助。包括你当前的代码、它的输出,以及你卡住的确切位置的描述。
  • How can I archive this using Regex? 嗯也许是写正则表达式?
  • 是的。我想写一个正则表达式。
  • 嗯。也许我会先试一试。
  • 从外观上看,它似乎是一个 XML 字符串。为什么要使用 RegEx 而不是 LINQ to XML?

标签: c# regex xml


【解决方案1】:

这个正则表达式提取 3 个组:

 <seg_(\d+)\sstatus=(\d+)>(.*?)<\/seg_\1>
 Full match 0-44    `<seg_0 status=0>This is segment zero</seg_0>`
 Group 1.   5-6 `0` -> index
 Group 2.   14-15   `0` -> status
 Group 3.   16-36   `This is segment zero` ->segment text

要提取字符串中的所有匹配项,请使用/&lt;seg_(\d+)\sstatus=(\d+)&gt;(.*?)&lt;\/seg_\1&gt;/g

【讨论】:

  • 我试试看。
  • 我现在有一个结果:var myString = "这是第 0 段这是第 1 段这是第二段";正则表达式 = new Regex(@"(.*?)");匹配 match = pattern.Match(myString); foreach(var item in match.Groups) { string value = item.ToString(); } 匹配只包含第一段。我怎样才能得到其余部分?
  • 您的解决方案现在是正确的。我即将完成我的解决方案的示例代码。 :D
  • 添加g 进行全球搜索:/&lt;seg_(\d+)\sstatus=(\d+)&gt;(.*?)&lt;\/seg_\1&gt;/g
【解决方案2】:

您可以尝试以下 regex 来捕获所有段并通过将它们替换为捕获的组来创建一个数组:

input >>  <seg_0 status=0>This is segment zero</seg_0>
          <seg_1 status=1>This is segment one</seg_1>
          <seg_2 status=0>This is segment two</seg_2> 
regex >>  <seg_(\d+)[\s\w]+=(\d+)>([\w\s]+)<\/seg_\d+> 
replace with >>  {"index":"$1","status":"$2","seg":"$3"},
output >>  {"index":"0","status":"0","seg":"This is segment zero"},
           {"index":"1","status":"1","seg":"This is segment one"},
           {"index":"2","status":"0","seg":"This is segment two"},

demo / explanation

C# (可能)

using System;
using System.Text.RegularExpressions;

public class RegEx
{
    public static void Main()
    {
        string pattern = @"<seg_(\d+)[\s\w]+=(\d+)>([\w\s]+)<\/seg_\d+>";
        string substitution = @"{""index"":""$1"",""status"":""$2"",""seg"":""$3""},";
        string input = @"<seg_0 status=0>This is segment zero</seg_0><seg_1 status=1>This is segment one</seg_1><seg_2 status=0>This is segment two</seg_2>";

        Regex regex = new Regex(pattern);
        string result = regex.Replace(input, substitution);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2013-06-28
    • 1970-01-01
    相关资源
    最近更新 更多