只需使用String.IndexOf()
来查找下一个管道。如果前一个字符不是反斜杠,则使用String.Substring()
来提取该单词。或者,您可以使用String.IndexOfAny()
来查找管道或反斜杠的下一个匹配项。
我做了很多像这样的解析,而且这非常简单。采取我的方法,如果正确完成,也会趋于更快运行。
编辑
事实上,也许这样的事情。有趣的是,看看它如何比较RegEx解决方案的性能。
public List<string> ParseWords(string s)
{
List<string> words = new List<string>();
int pos = 0;
while (pos < s.Length)
{
// Get word start
int start = pos;
// Get word end
pos = s.IndexOf('|', pos);
while (pos > 0 && s[pos - 1] == '\\')
{
pos++;
pos = s.IndexOf('|', pos);
}
// Adjust for pipe not found
if (pos < 0)
pos = s.Length;
// Extract this word
words.Add(s.Substring(start, pos - start));
// Skip over pipe
if (pos < s.Length)
pos++;
}
return words;
}
你见过[this(monster)thread](http://stackoverflow.com/questions/2148587/regex-quoted-string-with-escaped-quotes-in-c)。不是一个直接的答案,但希望推动正确的方向。 – dawebber 2011-04-28 04:32:58
如果你想在其中一块的末尾有文字反斜杠怎么办? – Random832 2011-04-28 04:42:28