代码之家  ›  专栏  ›  技术社区  ›  user2970916

将字符串拆分为两个字符子字符串的正则表达式模式

  •  2
  • user2970916  · 技术社区  · 8 年前

    假设我们有以下字符串:

    string str = "Idno1";
    string pattern = @"\w{2}";
    

    使用上面的模式将得到“Id”和“no”,但它将跳过“1”,因为它与模式不匹配。我希望得到以下结果:

    string str = "Idno1"; // ==> "Id" "no" "1 "
    string str2 = "Id n o 2"; // ==> "Id", " n", " o", " 2" 
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Antoine V    8 年前

    Linq可以简化代码。 Fiddle 版本工程

    想法:我有一个 chunkSize =2作为你的要求,那么, Take Join 他们去 string .

    public static IEnumerable<string> ProperFormat(string s)
        {
            var chunkSize = 2;
            return s.Where((x,i) => i % chunkSize == 0)
                   .Select((x,i) => s.Skip(i * chunkSize).Take(chunkSize))
                   .Select(x=> string.Join("", x));
        }
    

    Idno1 --> 
    Id
    no
    1
    
    Id n o 2 -->
    Id
     n
     o
     2
    
        2
  •  0
  •   Aleks Andreev Md. Suman Kabir    8 年前

    在这种情况下Linq确实更好。您可以使用此方法-它将允许将字符串分成任意大小的块:

    public static IEnumerable<string> SplitInChunks(string s, int size = 2)
    {
        return s.Select((c, i) => new {c, id = i / size})
            .GroupBy(x => x.id, x => x.c)
            .Select(g => new string(g.ToArray()));
    }
    

    public static IEnumerable<string> SplitInChunksWithRegex(string s, int size = 2)
    {
        var regex = new Regex($".{{1,{size}}}");
        return regex.Matches(s).Cast<Match>().Select(m => m.Value);
    }