Reputation: 17418
This is an extension to this SO question. This question considers two different enclosing characters, in contrast to the original question.
I would like to split by (white)spaces of any number but ignore everything between <> AND "". So this string:
string Line = "1 2 <1 2> \"hello world\" 3";
Should result in this:
1, 2, <1 2>, \"hello world\", 3
Upvotes: 3
Views: 680
Reputation: 17418
This is what I came up with so far:
public static string[] GetSplitStrings(string input)
{
IList<string> splitStrings = new List<string>();
var counter = 0;
var sb = new StringBuilder();
var inLessGreater = false; // sometimes <> can contain "
foreach (var character in input)
{
if (character.Equals('<'))
{
inLessGreater = true;
counter++;
}
if (character.Equals('>'))
{
inLessGreater = false;
counter++;
}
if (character.Equals('"') && !inLessGreater)
{
counter++;
}
if ((character.Equals(' ') && counter == 0) || (counter == 2))
{
if (sb.ToString().Equals("") == false)
{
if (character.Equals('"') || character.Equals('>'))
{
sb.Append(character);
}
splitStrings.Add(sb.ToString());
}
sb.Clear();
counter = 0;
}
else
{
sb.Append(character);
}
}
return splitStrings.ToArray();
}
Would prefer a neat regex solution.
Upvotes: 0
Reputation: 116168
Instead of Split
, I'll use Matches
string Line = "1 2 <1 2> \"hello world\" 3";
var parts = Regex.Matches(Line, @"[<\""]{1}[\w \d]+?[>\""]{1}|[\w\d]+")
.Cast<Match>()
.Select(m=>m.Value)
.ToArray();
PS: This would also match "abc def>
. But I ignored it to make the regex shorter
Upvotes: 3