/// <summary> /// Will call 'token' for every found token/specifier. /// First argument is the substring, second argument is true if this is a literal. /// </summary> public static void TokenizeFormatString(string format, TokenDelegate token) { if (string.IsNullOrEmpty(format)) { return; } bool isQuote = false; int idx = 0; int idxStart = 0; char currentChar = '\0'; for (; idx < format.Length; ++idx) { char c = format[idx]; if (idx != idxStart) { bool needsFlush = (!isQuote && (c != currentChar || c == '%')) || c == '\'' || c == '\\'; if (needsFlush) { token(idxStart, idx - idxStart, isQuote); idxStart = idx; } } if (c == '\'') { isQuote = !isQuote; idxStart = idx + 1; continue; } if (c == '\\') { if (idx == format.Length - 1) { throw new FormatException(); } token(idx + 1, 1, true); idx += 1; idxStart = idx + 1; continue; } if (!isQuote && c == '%') { if (idx == format.Length - 1) { throw new FormatException(); } token(idx + 1, 1, false); idx += 1; idxStart = idx + 1; continue; } currentChar = c; } if (isQuote) { throw new FormatException(); } if (idxStart != idx) { token(idxStart, idx - idxStart, false); } }
/// <summary> /// Will call 'token' for every found token/specifier. /// First argument is the substring, second argument is true if this is a literal. /// </summary> public static void TokenizeFormatString(string format, TokenDelegate token) { if (string.IsNullOrEmpty(format)) return; bool isQuote = false; int idx = 0; int idxStart = 0; char currentChar = '\0'; for (; idx < format.Length; ++idx) { char c = format[idx]; if (idx != idxStart) { bool needsFlush = (!isQuote && (c != currentChar || c == '%')) || c == '\'' || c == '\\' ; if (needsFlush) { token(idxStart, idx - idxStart, isQuote); idxStart = idx; } } if (c == '\'') { isQuote = !isQuote; idxStart = idx + 1; continue; } if (c == '\\') { if(idx == format.Length - 1) throw new FormatException(); token(idx + 1, 1, true); idx += 1; idxStart = idx + 1; continue; } if (!isQuote && c == '%') { if (idx == format.Length - 1) throw new FormatException(); token(idx + 1, 1, false); idx += 1; idxStart = idx + 1; continue; } currentChar = c; } if(isQuote) throw new FormatException(); if (idxStart != idx) { token(idxStart, idx - idxStart, false); } }