我的文本文件的值为
"444","/5"," ", " "," john""66""88"
我想只获得带双引号的值 分裂后我想要七个字符串如下所示
first = "444"
second = "/5"
third = " "
fourth =" "
fifth = "john"
sixth= "66"
seven= "88"
.Split("' '")
似乎无法正常工作
答案 0 :(得分:2)
使用正则表达式而不是拆分,如果由于某种原因在引用文本中有逗号并且您用逗号分割,那么您的数据将被破坏。
使用此:
Regex reg = new Regex("\"([^\"]*?)\"");
List<string> elements = new List<string>();
var matches = reg.Matches(theExpression);
foreach(Match match in matches)
{
var theData = match.Groups[1].Value;
elements.Add(theData);
}
//Now you have in elements a list with all
//the values from the string properly splitted.
答案 1 :(得分:0)
我刚刚发现,您的部件可能不会以逗号分隔。这是一种基于char的方法:
A
您可以像这样尝试
string s = "\"444\",\"/5\",\" \", \" \",\" john\"\"66\"\"88\"";
var myParts = new List<string>();
int pos1 = s.IndexOf('"');
if (pos1 == -1)
throw new Exception("No qoutes!");
int pos2 = s.IndexOf('"', pos1 + 1);
if (pos1 == -1)
throw new Exception("No second quote!");
while (true) {
myParts.Add(s.Substring(pos1, pos2 - pos1 + 1));
pos1 = s.IndexOf('"', pos2 + 1);
if (pos1 == -1)
break;
pos2 = s.IndexOf('"', pos1 + 1);
if (pos2 == -1)
throw new Exception("No final closing quote!");
};