如果我有一个像这样的字符串:
我该如何解析它,以便得到以下内容的三个字符串“单词”:
create myclass "56, 'for the better or worse', 54.781"
我该如何解析它,以便得到以下内容的三个字符串“单词”:
[0] create
[1] myclass
[2] "56, 'for the better or worse', 54.781"
编辑2:请注意引号需要保留
起初,我尝试使用string.Split(' ')
,但我发现它会将第三个string
分成几个字符串。
我尝试通过在Split
中使用count
参数作为3
来限制结果数量以解决这个问题。对于这种情况,这样做没问题,但当给出的字符串是:
create myclass false "56, 'for the better or worse', 54.781" //or
create myclass "56, 'for the better or worse', 54.781" false
由于最后两个单词会被合并,因此拆分失败。
我还创建了类似于ReadInBetweenSameDepth
的东西,以获取引号之间的string
这是我的ReadInBetweenSameDepth
方法
//Examples:
//[1] (2 + 1) * (5 + 6) will return 2 + 1
//[2] (2 * (5 + 6) + 1) will return 2 * (5 + 6) + 1
public static string ReadInBetweenSameDepth(string str, char delimiterStart, char delimiterEnd) {
if (delimiterStart == delimiterEnd || string.IsNullOrWhiteSpace(str) || str.Length <= 2)
return null;
int delimiterStartFound = 0;
int delimiterEndFound = 0;
int posStart = -1;
for (int i = 0; i < str.Length; ++i) {
if (str[i] == delimiterStart) {
if (i >= str.Length - 2) //delimiter start is found in any of the last two characters
return null; //it means, there isn't anything in between the two
if (delimiterStartFound == 0) //first time
posStart = i + 1; //assign the starting position only the first time...
delimiterStartFound++; //increase the number of delimiter start count to get the same depth
}
if (str[i] == delimiterEnd) {
delimiterEndFound++;
if (delimiterStartFound == delimiterEndFound && i - posStart > 0)
return str.Substring(posStart, i - posStart); //only successful if both delimiters are found in the same depth
}
}
return null;
}
虽然这个函数能够工作,但我发现将结果与string.Split
结合起来以实现我想要的正确解析相当困难。
编辑2:在我的糟糕解决方案中,我需要稍后重新添加引号
有没有更好的方法来解决这个问题?如果我们使用Regex
,该如何操作?
编辑:
我真的不知道这个问题可以像CSV格式的文本一样解决。我也不知道这个问题不一定要通过Regex
来解决(因此我将其标记为这样)。对于那些认为这是重复帖子的人,我真诚地道歉。
编辑2:
在我的项目上工作了更多之后,我意识到我的问题有些问题(即,我没有包括引号)- 向先前最佳答案者Tim Schmelter先生道歉。然后,在查看重复链接后,我注意到它也没有提供解决方案。
parser.HasFieldsEnclosedInQuotes = true; parser.SetDelimiters(separator); string[] fields = null; while (!parser.EndOfData) fields = parser.ReadFields(); parser.Close(); return fields; }`。将空格设置为分隔符,就这样,很安全。添加 `using Microsoft.VisualBasic.FileIO;` 和 `System.IO;`。
- Wiktor StribiżewTextFieldParser
是像 TimSchmelter 先生说的那样最好的方法。谢谢,我会去查看一下的。 - Ian