【问题标题】:c# Regex Split Binary String时间:2019-04-01 标签:c#regexsplitbinarystring
【发布时间】:2020-05-07 07:01:12
【问题描述】:

我正在尝试以特定方式拆分一串二进制数字

假设这是我的字符串100011001110010101110

我想在 1

之前的每个 0 处拆分字符串

所以上面分割后的字符串就变成了

1000 1100 11100 10 10 1110

我使用了正则表达式模式/(1+0+)/g,它正确地拆分了字符串,但它错过了一些组。 这是c#代码

Regex.Split(stringToSplit, @"(1+0+)");

请问我做错了什么。

编辑:我没有提到我确信 1 将总是先于 0

提前致谢。

【问题讨论】:

    标签: c# regex split


    【解决方案1】:

    你可以试试看aheadbehind,即用0behind散落在零长度文本上> 分裂和1 ahead

    代码:

      string source = "100011001110010101110";
    
      var result = Regex.Split(source, "(?<=0)(?=1)");
    
      // Let's have a look
      Console.Write(string.Join(Environment.NewLine, result));
    

    结果:

    1000
    1100
    11100
    10
    10
    1110
    

    编辑:图案(?&lt;=0)(?=1)解释:

    (?<=0) - 0 should be behind the split
           - empty; split on epmty (zero-length) text
    (?=1)  - 1 should be ahead of the split
    

    所以我们有

    1000 110011
       ^^^
       |||- 1 should be ahead of split
       ||--   split here
       |--- 0 should be behind the split
    

    【讨论】:

    • 不错!你能添加更多关于模式的解释吗?
    • 这就像一个魅力。无需额外处理,即可获得所需的准确结果。
    【解决方案2】:

    问题是您的正则表达式模式返回多个匹配项,如您所见 Here

    您可以改为使用 .Matches() 检索值。

    Regex.Matches("100011001110010101110", "(1+0+)").Cast<Match>().Select(x => x.Value);
    

    【讨论】:

    • 您将丢失所有前导零或尾随零(如果存在)。
    • 这可行,但似乎 Cast 和 Select 增加了执行时间。感谢您的回复。
    【解决方案3】:

    代码:

    var input = "100011001110010101110";
    var results = Regex.Split(input, @"(1+0+)")
                            .Where(n => !string.IsNullOrEmpty(n))
                            .ToList();
    Console.WriteLine(string.Join("\n", results));
    

    结果:

    1000
    1100
    11100
    10
    10
    1110
    Press any key to continue . . .
    

    【讨论】:

      猜你喜欢
      • 2016-10-23
      • 2011-01-31
      • 2013-04-11
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多