1

我面临一个有趣的 C# 字符串拆分问题。我有以下需要拆分为键/值对的数据。问题是数据本身并没有很好地分隔空格字符。

样本数据:

Somefield1:500 Somefield2:atextfield Somefield3:a text field with spaces Somefield4:102 Somefield5whichisblank: somefeild6:m0redata somefeild7:(1,2,3     5)

我尝试使用的方法使用正则表达式匹配分隔空格字符:

var lineOfText = @"Somefield1:500 Somefield2:atextfield Somefield3:a text field with spaces Somefield4:102 Somefield5whichisblank: somefeild6:m0redata somefeild7:(1,2,3     5)"
foreach (string match in Regex.Split(lineOfText, @"\s(?=[^\)]*(?:\(|$))").Where(s => s != String.Empty))
      {
       // Split into key / value pairs here
      }

问题出在我的正则表达式上。我认为解决方案很接近,但是它当前在字段之间匹配空格。 gskinner 示例在这里

如果有人可以协助修复我的正则表达式以不匹配“中间”空间,或者提供一种超级的替代方法。

再次感谢。

4

1 回答 1

4

尝试使用这个正则表达式:\s(?=\w+:)

于 2013-08-16T02:36:31.017 回答