【问题标题】:Split into string array only the key by comma and not values c#只用逗号分割成字符串数组,而不是值c#
【发布时间】:2020-01-03 06:38:17
【问题描述】:

这是我的字符串,我在拆分为字符串数组时遇到问题,键的逗号分隔值

{ Yr = 2019, Mth = DECEMBER , SeqN = 0, UComment = tet,tet1, OComment = test,test1, FWkMth = WK, FSafety = Y, FCustConsign = Y, FNCNRPull = 0, FNCNRPush = 0, CreatedTime = 2020-01-03 06:16:53 }

当我尝试使用 string.Split(',') 时,我得到 "Ucomment = tet","tet1" 作为单独的数组。 但是当用逗号分隔时我需要拆分字符串[]

UComment = tet,tet1 OComment = test,test1

我尝试过使用正则表达式 ,(?=([^\"]\"[^\"]\")[^\"]$) " 但它没有用。

【问题讨论】:

  • 您的预期输出在这里是什么样的?
  • @tim-biegeleisen,它是 sring 数组,它会像 "Yr = 2019", "Mth = DECEMBER", "SeqN = 0", "UComment = tet,tet1"

标签: strsplit


【解决方案1】:

您可以尝试匹配正则表达式模式\S+\s*=\s*.*?(?=\s*,\s*\S+\s*=|\s*\}$):

string input = "{ Yr = 2019, Mth = DECEMBER , SeqN = 0, UComment = tet,tet1, OComment = test,test1, FWkMth = WK, FSafety = Y, FCustConsign = Y, FNCNRPull = 0, FNCNRPush = 0, CreatedTime = 2020-01-03 06:16:53 }";
Regex regex = new Regex(@"\S+\s*=\s*.*?(?=\s*,\s*\S+\s*=|\s*\}$)");
var results = regex.Matches(input);
foreach (Match match in results)
{
    Console.WriteLine(match.Groups[0].Value);
}

打印出来:

Yr = 2019
Mth = DECEMBER
SeqN = 0
UComment = tet,tet1
OComment = test,test1
FWkMth = WK
FSafety = Y
FCustConsign = Y
FNCNRPull = 0
FNCNRPush = 0
CreatedTime = 2020-01-03 06:16:53

这里是使用的正则表达式模式的解释:

\S+                        match a key
\s*                        followed by optional whitespace and
=                          literal '='
\s*                        more optional whitespace
.*?                        match anything until seeing
(?=\s*,\s*\S+\s*=|\s*\}$)  that what follows is either the start of the next key/value OR
                           is the end of the input

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多