Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Linq;
- namespace TableParser
- {
- public class FieldsParserTask
- {
- public static List<string> ParseLine(string line)
- {
- var list = new List<string>();
- if (line.Length == 0)
- return list;
- var quoteIndex = 0;
- var simple = GetFirstFieldType(line);
- MainBlock(line, list, quoteIndex, simple);
- return list;
- }
- public static void MainBlock(string line, List<string> list, int quoteIndex, bool simple)
- {
- for (var i = 0; i < line.Length; i++)
- {
- if (simple)
- {
- i = GetIndexNextToToken(line, quoteIndex);
- if (i == -1)
- {
- list = AddFieldWithoutClosingQuote(line, list, quoteIndex);
- return;
- }
- else
- if (i != line.IndexOfAny(new char[] { '\'', '\"' }))
- i += quoteIndex + 1;
- simple = false;
- list = AddSimpleField(line, list, quoteIndex, i);
- quoteIndex = i;
- continue;
- }
- if (!simple)
- ComplexField(line, list, ref quoteIndex, ref simple, ref i);
- }
- }
- private static void ComplexField(string line, List<string> list, ref int quoteIndex, ref bool simple, ref int i)
- {
- for (var k = quoteIndex + 1; k < line.Length; k++)
- {
- if (line[k] == '\\')
- {
- k++;
- continue;
- }
- if (line[k] == line[quoteIndex])
- {
- i = k;
- list.Add(DeleteSlash(line.Substring(quoteIndex + 1, k - quoteIndex - 1)));
- quoteIndex = k;
- simple = true;
- break;
- }
- if (k + 1 == line.Length)
- {
- i = line.Length - 1;
- list.Add(DeleteSlash(line.Substring(quoteIndex + 1)));
- break;
- }
- }
- }
- public static List<string> AddSimpleField(string line, List<string> list, int quoteIndex, int i)
- {
- if (quoteIndex == 0)
- list.AddRange(GetSplitedSimpleField(line.Substring(quoteIndex, i - quoteIndex)));
- else
- list.AddRange(GetSplitedSimpleField(line.Substring(quoteIndex + 1, i - quoteIndex - 1)));
- return list;
- }
- public static List<string> AddFieldWithoutClosingQuote(string line, List<string> list, int quoteIndex)
- {
- if (quoteIndex != 0)
- quoteIndex++;
- list.AddRange(line.Substring(quoteIndex)
- .Split(' ')
- .Where(x => x != ""));
- return list;
- }
- public static int GetIndexNextToToken(string line, int quoteIndex)
- {
- var i = 0;
- if (quoteIndex != 0)
- i = line.Substring(quoteIndex + 1).IndexOfAny(new char[] { '\'', '\"' });
- else
- i = line.IndexOfAny(new char[] { '\'', '\"' });
- return i;
- }
- public static bool GetFirstFieldType(string line)
- {
- var simple = true;
- if (line[0] == '\'' || line[0] == '\"')
- simple = false;
- return simple;
- }
- public static List<string> GetSplitedSimpleField(string line)
- {
- return line
- .ToString()
- .Split(' ')
- .Where(x => x != "")
- .ToList();
- }
- public static string DeleteSlash(string line)
- {
- return line
- .Replace("\\\\", "\\")
- .Replace("\\'", "'")
- .Replace("\\\"", "\"");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement