【问题标题】:Split string on the '.' dot characters that are not inside of [] brackets在 '.' 上拆分字符串不在 [] 括号内的点字符
【发布时间】:2016-02-15 20:36:35
【问题描述】:

我有一些类似的字符串:

"Item.ObjectA.ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11].ObjectD.Value"

如果我将它与. 分开,它会给出:

物品

对象A

ObjectBs[Id=1234;Name=Test;Date=12

05

2016 年 11:11:11]

对象D

价值

但我想要一个结果,忽略[] 内的点,即:

物品

对象A

ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11]

对象D

价值

我怎样才能简单地做到这一点?

【问题讨论】:

  • \.(?![^[]*\]) 可能会起作用 - regex101.com/r/nI4cQ5/1
  • 它与 regex.split 一起工作。谢谢!
  • 如果需要转义括号:\.(?![^\[]*\])

标签: c# .net regex string split


【解决方案1】:

将我的评论移至答案:

一种选择是使用负前瞻来匹配 . 字符后面没有零个或多个 [ 字符,然后是 ] 字符:

\.(?![^[]*\])

Live Example:

string pattern = @"\.(?![^[]*\])";
string input = "Item.ObjectA.ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11].ObjectD.Value";

foreach (String split in Regex.Split(input, pattern))
{
    Console.WriteLine(split);
}

输出:

物品

对象A

ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11]

对象D

价值


或者,您也可以根据以下表达式进行匹配,而不是拆分字符串:

[^.]*\[[^]]*\]|[^.]*

Live Example:

string pattern = @"[^.]*\[[^]]*\]|[^.]*";
string input = "Item.ObjectA.ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11].ObjectD.Value";
foreach (Match match in Regex.Matches(input, pattern))
{
    Console.WriteLine(match.Value);
}

同样的输出。

【讨论】:

    【解决方案2】:

    这个答案展示了如何在纯编程中做到这一点

    using System;
    using System.Collections.Generic;                   
    using System.Text;
    using System.Linq;
    
    public class Program
    {
    
        public static void Main()
        {
    
            var orig = "Item.ObjectA.ObjectBs[Id=1234;Name=Test;Date=12.05.2016 11:11:11].ObjectD.Value";
    
            var parts = new List<string>();
            var stop = false;
            var current = new StringBuilder();
    
            for (int i = 0; i < orig.Length; i++)
            {
    
                if (orig[i] != '.')
                    current.Append(orig[i]);
    
                if (orig[i] == '[')
                    stop = true;
    
                if (orig[i] == ']')
                    stop = false;
    
                if ((orig[i] == '.' && !stop) || i == orig.Length - 1)
                {
                    parts.Add(current.ToString());
                    current.Length = 0;
                }
    
    
            }
    
            parts.ForEach(x =>  Console.WriteLine(x));
        }
    }
    

    结果 Item ObjectA ObjectBs[Id=1234;Name=Test;Date=12052016 11:11:11] ObjectD Value

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 2022-12-06
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多