Skip to main content
 首页 » 编程设计

c#之正则表达式:忽略字段之间的空格

2024年02月13日31pengyingh

我遇到了一个有趣的 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 example here .

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

再次感谢。

请您参考如下方法:

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